Warning message

Documentation is currently being migrated into the new system. Some pages might be temporarily missing, and some guides might appear empty. Thank you for your patience while we are improving Drupal.org documentation.

Adding CSS to form or page with attachments

Last updated on
September 23, 2016 - 22:08

This documentation is incomplete. Add more information.

On previous pages we learned how to add css using the .info file and the drupal_add_css() function. You will recall that the major advantage to drupal_add_css() is that you can include CSS only on specific pages to reduce your page load. Unfortunately, if you have a lot of conditional rules about what CSS to include where, this can lead to complex logic in your template.php or in a hook_init() implementation. Thankfully, there's an easier way!

Adding css using #attached attribute

Drupal 7 introduced render arrays to improve the separation of content and markup. One of the special elements of a render array is the #attached attribute. This attribute allows you to declaratively state what CSS needs to be included whenever that array is rendered into HTML.

Adding CSS to a cached block

Sometimes we try to add css using drupal_add_css() inside hook_block_view(), but it is not included because block is cached.

Here is an example of cached block without #attached

function foo_block_view($delta = ''){
  if ($delta == 'foo_delta') {
    $block = array( 'subject' => t('Foo title'), 'content' => t('Lorem ipsum text.');
    return $block;

Initially above code will work, but if you turn on caching, or if you have defined your block to be cached in hook_block_info(), the my.css will fail to be included.

Now #attached attribute can resolve this problem because it associated with rendered array that always rendered.

Here is example of #attached attribute

function foo_block_view($delta = '')
{ if ($delta == 'foo_delta') { $block = array( 'subject' => t('Foo title'), 'content' => array( '#markup' => ' . t('Lorem ipsum text.') . ', '#attached' => array( 'css' => array('path/to/my.css'), ), ), ); return $block; } } 

Now content element coming as a render array having two elements #markup and #attached both will always be included. We can add internal, external and inline css using this attribute.

We can also add css to page in similar way.

$content = array(); $content['#attached']['css'] = array( $path . 'my.css' => array( 'group' => CSS_AGGREGATE_THEME, 'weight' => 999 ), ); return $content;