Last updated August 12, 2015. Created on June 3, 2014.
Edited by rashid_786, mpgeek, camorim, er.pushpinderrana. Log in to edit this page.

On previous page we learn how to add css using .info file and drupal_add_css(). Adding custom CSS to a page is easy in Drupal, but can be a little bit messy when caching is enabled there and you need to choose best approach to use.

Adding css using #attached attribute

Drupal 7 introduced rendered arrays and one of the special elements of a render array is the #attached attribute. Best thing about this attribute is it make sure your css would always be included because it comes with rendered array.

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') {
    drupal_add_css('path/to/my.css');
    $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;

Even in Drupal 8, adding css to the page should now be done using the #attached property of a rendered array. You can checkout this here.

Looking for support? Visit the Drupal.org forums, or join #drupal-support in IRC.