Multiple CSS Classes on an Element

One of the lesser known features of Cascading Style Sheets is the ability to apply more than one class to a single element. Browser support for this is pretty good and goes back at least as far as Internet Explorer 6. I needed to put this feature to use, so I did a few experiments on how it works and thought I would share my notes here.

To give an element more than one class you just separate the class names with spaces. Below is an example of a div with three classes.

<div class="one two three"></div>

A couple of things I found about using multiple classes are:

  1. The order of the classes makes no difference. class=”one two” is the same as class=”two one”. Standard inheritance applies and if the classes are at the same level of inheritance (i.e. both classes are defined in style tags) the class that is defined last will have its rules take priority.
  2. In Javascript, the className property returns all class names in a string (getAttribute(’class’) returns the same, doesn’t work in IE6).
  3. Also in Javascript if you are looking for a particular class it can be handy to use split to divide the className property into an array.
    String(document.getElementById('test').className).split(' ')

You can see the example code in action by clicking here. Take a look at the source to see how the multiple classes interact and override each other the generate the final look of the div.

Leave a Reply

{
}