How to Set Custom Body CSS Class in a Joomla 1.5 Template

body tag

Joomla has a built-in page class suffix option that adds a suffix to the CSS class of your content container and page title, but in my experience, this is just not enough. More often than not, I need to change something outside of the main content container, like the background image or sidebar width. The only way to control these items for an individual page is by setting the body CSS class to a unique class. This can easily be done by adding a snippet of code to your Joomla 1.5 template. Add the code below to your body tag.

class="<?php
function getMenuName()    {       global $Itemid;       $name = getMenu($Itemid);       $name = ereg_replace('[/ ]', "", strtolower($name));       return $name;    }        function getMenu($itemid)    {       global $db; 	  $db = JFactory::getDBO();       $db->SetQuery( "SELECT alias FROM #__menu WHERE id='$itemid'");
return $db->loadResult();
}

echo getMenuName();

?>"

The result is a body tag that matches the current menu item alias. For example: If you are on the about us page and the menu alias is “about-us,” the body class will be “aboutus” (no dashes).

This will give you more fine grained control of your CSS styles for individual pages. Enjoy!

Update: I have written a new post showing you how to set the body tag as the page class suffix.

Be Sociable, Share!
Tarik Assagai
Tarik (@tarik916) is a web developer and owner of ACS Digital Media, a Sacramento based web development agency specializing in open source CMS systems. If you are looking for support for your current or upcoming projects, visit www.acs-digital.com.

15 Comments

  1. Nice Tip but what if I want to add the page_suffix attribute to the body tag instead of the title’s alias.

  2. This is what I needed, but where do I need to put to code?
    In index.php?

  3. tarik916 /

    Yes, you would place this code in the index.php file of your template. This file is located under /templates/yourtemplate/index.php.

  4. Hey there, thanks so much for this post, you really saved my a**! As I wanted to easily change CSS styling based on categories, I made some alterations so that the code returns the Category number instead of the menu item:

    function getCatNum()
    {
    global $Itemid; $name = getCategory($Itemid);
    return $name;
    }

    function getCategory($itemid) { global $db; $db = JFactory::getDBO();
    //$db->SetQuery( “SELECT alias FROM #__menu WHERE id=’$itemid'”);
    $db->SetQuery( “SELECT catid FROM #__content WHERE id=’$itemid'”);

    return $db->loadResult();
    }

  5. Thanks, but it’d be better if you also mention the location of html file, I googled it and now it’s fixed

Trackbacks/Pingbacks

  1. How to set body CSS class as page class suffix in your Joomla! template | Slurp it up! I'm talking about the web. - [...] a previous post, I showed you how to set the menu alias as the body CSS class in Joomla!. …

Leave a Reply