Drupal - Adding a class to “body”
The documentation for the html.tpl.php template documents the $classes
variables as String of classes that can be used to style contextually through CSS.. If you look at the code for the template, this variable is used in the class attributes of the produced body element:
<body class="<?php print $classes; ?>" <?php print $attributes;?>>
The $classes
variables is actually already set by template_process()
for any template file and build from the content of the $classes_array
variable.
So to add a class to the body of your page, you should add this class to the $classes_array
value from your theme (or module)'s implementation of hook_preprocess_html()
:
function THEME_preprocess_html(&$variables) {
$variables['classes_array'][] = 'new-class';
}
Since this is the core defined template and process function, any well-behaving theme should re-use the same variables.
In your theme's template.php
file use the preprocess_html
hook:
function mytheme_preprocess_html(&$vars) {
$vars['classes_array'][] = 'new-class';
}
Remember to clear the caches once you've implemented the hook or Drupal won't pick it up.
The Context module allows you to add a class to the body tag as well.
This can be useful if you need the class to be added under certain conditions.
You find this options under the reaction "Theme HTML" :
I had to use different array keys in the same hook to make it work:
function THEME_preprocess_html(&$vars) {
$vars['attributes_array']['class'][] = 'foo2';
}