Adding styles through the API

Last updated on
31 August 2016

Adding styles through the .info file should be sufficient for most themes. Since the .info file is static, style sheets cannot be added dynamically. Depending on how the theme handles style sheets, it may not matter altogether. When in doubt, use the .info file.

There are two API functions for working with style sheets, drupal_add_css and drupal_get_css. Here is an example to dynamically add styles sheets.

Change the "template" prefix to the name of your theme.

function template_preprocess_page(&$variables) {
  $front_style = path_to_theme() .'/front-page.css';
  $path_style = path_to_theme() .'/path-'. arg(0) .'.css';

  if (file_exists($front_style) && $variables['is_front']) {
    $include_style = $front_style;
  }
  elseif (file_exists($path_style)) {
    $include_style = $path_style;
  }

  if (isset($include_style)) {
    drupal_add_css($include_style, 'theme', 'all', FALSE);
    $variables['styles'] = drupal_get_css();
  }
}

The above example would include the style sheet "front-page.css" on the front page or many others based on the internal path. For example, http://example.com/admin would pickup on "path-admin.css".

A few notes:

  • Depending on where and when the style is added, drupal_get_css may need to be called in order to include the added styles. They are initially retrieved in template_preprocess_page. See Preprocessors and variables for details on the order of the preprocessors.
  • There is a parameter in drupal_add_css to aggregate the added file. Consider disabling it like the above example when the inclusion of the style sheet is very dynamic, since files added to the larger aggregate will force a new aggregated CSS file to be recreated. In effect, it can slow down the retrieval of the page and consume more bandwidth.

Where To Add Code

This code can be added in the template.php file in your theme directory.
There may already be a function there called "phptemplate_preprocess_page".
Just include it within the body of your XXX__preprocess_page function.

You may also need to change "variables" to "vars" to make it work. You just have to use the same variable name that is passed in by reference within your function. For example, if your function signature looks like ...
function template_preprocess_page(&$vars)
then you should use
$vars
inside the function.