Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a class to "body"

How can I modify or pre-process the <body> tag to add the class body? I don't want to create a whole html.tpl.php just to add a class.

like image 700
Chris Muench Avatar asked Oct 09 '11 01:10

Chris Muench


People also ask

Can you add a class to the body element?

We used the add() method to add a class on the body object. We can access the body element on the document object. If the class is already present on the body element, it won't get added twice. You can pass as many classes to the add() method as necessary.

Can you add class to HTML?

HTML. Using . add() method: This method is used to add a class name to the selected element.


2 Answers

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.

like image 87
Clive Avatar answered Sep 30 '22 18:09

Clive


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.

like image 23
Pierre Buyle Avatar answered Sep 30 '22 20:09

Pierre Buyle