Load Custom CSS for Each Joomla Component
During September and November, we migrated OSTraining.com to Joomla 2.5.
Our old Joomla 1.5 site had been live for years and had accumulated all sorts of junk, particularly when it came to CSS.
Here’s a useful trick we used to clean up our CSS and also make our site load faster.
Faster and Lighter CSS
We had a very messy and convoluted template system. We had 4 different templates, all with different and sometimes contradictory CSS.
So, for Joomla 2.5, we moved to one template for all our needs. However, we added many more CSS files.
Instead of loading all our CSS in one file, we created a new file for each component. This has two advantages:
- Organization: it’s much easier to see which CSS applies to which part of the site.
- Speed: because CSS is only loaded when it’s needed, much less CSS is loaded.
Loading the CSS
As with most Joomla templates, we load the CSS via our index.php file.
All of the following CSS will be added between the opening and closing head tags.
First we load the CSS as normal:
"/<?php echo $this->baseurl ?>/templates/<?php echo($this->template);?>/css/template.css"
Then we load the CSS for each extension:
"/<?php echo $this->baseurl ?>/templates/<?php echo($this->template);?>/css/<?php echo($option);?>.css"
The first line is a PHP if statement which check to see if a CSS file exists for the component currently being used.
If that CSS file exists, the second line loads that custom CSS.
The naming convention for our CSS files always included com_ so we end up creating files with names such as com_kunena.css.
Custom CSS Per Page
If you’d like to take this further, you can use HD-Custom CSS.
HD-Custom CSS is a simple module that allows you to add CSS styles not just to components but even to individual Joomla pages.Click here for a full tutorial on using HD-Custom CSS.