Add CSS style for a block into the same block

This simple code can be pasted into a PHP filtered block (or into a block declared by a module) to set some style from a block into the block container itself.

<?php
echo 'My block content';
/** Put styles inline on html head**/
drupal_set_html_head('<style type="text/css">
#my-block-id {
  /* my style*/
}
</style>
');
?>

This code is placed on html head, applied only to the pages where block appears, without touching css optimization. If you want to include an external CSS file instead, use drupal_add_css instead: in any case you can exclude this file for aggregation, setting $preprocess attribute to FALSE.

If block appears in very few pages, and it can change quickly (e.g. a banner with custom styles on home page), using drupal_set_html_head could be the best way, even according to Yahoo Performance Best Practices. In other cases, use drupal_add_css.

See also:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s