[Drupal] How to add a custom class in the BODY tag in your Drupal site?

| | 2 min read

In one of my recent Drupal projects I needed to add some extra classes to the body tag. Usually classes are added to the body tag in one of our template file namely html.tpl.php. The classes can be added via an implementation of hook_preprocess_html. Now let's see how it can be done.

Consider the following implementation of hook_preprocess_html which adds a specific class to the body tag based on the number of sidebars present. Do note that 'my_theme' will have to be replaced with your theme name or your module name based on where you implement this hook.

<?php
function my_theme_preprocess_html(&$vars) {
  $right = (isset($vars['page']['sidebar_first'])) ? $vars['page']['sidebar_first'] : '';
  $left  = (isset($vars['page']['sidebar_second'])) ? $vars['page']['sidebar_second'] : '';
  if ($right & $left){
    $vars['classes_array'][] = 'col-3 ';
  }
  elseif($right && !$left) {
  	$vars['classes_array'][] = 'col-2-right ';
  }
  elseif($left && !$right) {
  	$vars['classes_array'][] = 'col-2-left ';
  }
  elseif(!$right && !$left) {
  	$vars['classes_array'][] = 'col-1 ';
  }
}
?>

The above code does the following things:

  1. The variables $right is set if the sidebar_first exists, and $left is set if sidebar_second exists.
  2. A class 'col-3' is added to the 'classes_array' if both $right and $left is set.
  3. A class 'col-2-right ' is added to the 'classes_array' if only $right is set.
  4. A class 'col-2-left ' is added to the 'classes_array' if only $left is set.
  5. A class 'col-1' is added to the 'classes_array' if none of the variables $right and $left is set.


The classes array in variables is then used to populate the classes in the body tag. You can use a similar approach to add your custom classes to the body tag in your Drupal project.