In this example we add an existing class to the #page element using template.php

The first thing to do is to open up the file named template.php with your preferred editor. This is located within your theme folder, usually found at: sites/all/themes/*yourtheme*/

If you are using an omega based theme it will look something like this:

  /**
  * @file
  * This file is empty by default because the base theme chain (Alpha & Omega) provides
  * all the basic functionality. However, in case you wish to customize the output that Drupal
  * generates through Alpha & Omega this file is a good place to do so.
  * 
  * Alpha comes with a neat solution for keeping this file as clean as possible while the code
  * for your subtheme grows. Please read the README.txt in the /preprocess and /process subfolders
  * for more information on this topic.
  */
 

Now add the following function underneath the comments shown above:

  function THEME_preprocess_page(&$vars, $hook) {
     //adds existing class to #page element
    $vars['attributes_array']['class'][]='newClass';
  } 

Where THEME_ is your theme name, and 'newClass' is the class you wish to add to the #page element.

Ensure you also have the <?php tag added to the very top of the document without any closing tags. This is essential in order to work.

You should end up with something like this:

<?php

/**
 * @file
 * This file is empty by default because the base theme chain (Alpha & Omega) provides
 * all the basic functionality. However, in case you wish to customize the output that Drupal
 * generates through Alpha & Omega this file is a good place to do so.
 * 
 * Alpha comes with a neat solution for keeping this file as clean as possible while the code
 * for your subtheme grows. Please read the README.txt in the /preprocess and /process subfolders
 * for more information on this topic.
 */
 
  function THEME_preprocess_page(&$vars, $hook) {
     //adds existing class to #page element
    $vars['attributes_array']['class'][]='newClass';
  } 

Now all you need to do is save the document and flush all caches

Comments

sierraoscardelta’s picture

Well for my use case I required a black background color on the body element, and a container that was 24 columns wide (960px) which had a different background color, multiple gradients, and an svg pattern that repeated on x and y axis. This could not be done effectively by applying these attributes and values to the zones concerned, due to lines being created at zone borders from svg pattern and gradients restarting.

This was the only sensible solution I found to achieve this.

imkartik’s picture

I recently faced an issue where I was not able to add a class in the body tag. The above solution did work earlier but now I have to use the snippet mentioned below:

$vars['classes_array'][] = 'new-class';