Add CSS File To Specific Pages In Drupal
I get asked a lot how to go about adding certain CSS files to only certain pages of a Drupal project, rather than every page. This is commonly desired when you are using a drastically different front page in comparison to your drill pages. To achieve this you will want to use the drupal_add_css() function provided by the Drupal API.
It’s very basic in functionality:
drupal_add_css(path_to_theme() . '/layout-fixed.css', 'theme', 'all');
Given a path to a CSS file, it will load it where ever the function is called. The second param specifies whether you are theming a “theme” or a “module” with it, and the third param reffers to the “media” attribute of the <link> tag.
I’ve seen many coders drop this call right into the page or node template they are theming. That is really less than desired, as it tightly links a css file to template file. Say you wanted to use this css file 5 times, you would have to add it to 5 files. That duplication would make it time-consuming to change if you had to alter the name of the file, for example (and that is provided you can remember where you put every call to drupal_add_css()).
A cleaner approach is to put it’s call in your template.php and use some logic to control when to use it. Something like:
if($_GET['q]=="node/2") {
drupal_add_css(path_to_theme() . '/crazy-style.css', 'theme', 'all');
}
Doing this will ensure that all of your dynamically added CSS’s files live in one spot, making it super easy to add or extend to.
To remove an existing CSS file per page, try something like:
$arrCSS = drupal_add_css();
unset($arrCSS['all']['theme']['path/to/css-file.css']);
$vars['styles'] = drupal_get_css($css);
return $vars;