CSS Ordering and Multiple Classes

I've recently needed to assign more than one CSS class to an html element. I didn't know this was possible until I tried it (I know a lot about CSS, just not everything).

You assign more than one class to an element by adding each class separated by a space to the class attribute of the element:

class="cssclassa cssclassb"

This works in both FF 2 and IE 6 & 7. I'm quite sure it works with everything else (someone can prove me wrong if they wish).

Afterwards, I wondered which CSS class will take precedence when more than one class assigns a different value to the same CSS property. So, I setup some CSS styles as follows:

<style type="text/css">
   .cssbgA {background-color:black;}
   .csscolorA {color:yellow;}
   .cssbgB {background-color:green;}
</style>

And setup a html element:

<p class="cssbgA csscolorA cssbgB">Here is some paragraph text.</p>

The browser output looks like this:

Output for <p>

If I rearrange the classes to:

<p class="cssbgB cssbgA csscolorA">Here is some paragraph text.</p>

The output is the same:

New output for <p>

Hmmm, nothing changed. So, I played with it for a minute or two and found that the display will change when the order of the classes is changed in the CSS itself; not the class attribute of the html element! So, if I change the CSS to:

<style type="text/css">
   .csscolorA {color:yellow;}
   .cssbgB {background-color:green;}
   .cssbgA {background-color:black;}
</style>

The output changes to:

The output has changed!

It seems the last class rendered by the browser takes precedence over previous classes.

Interesting. I guess I could have looked this up in the W3C specs. But I'm too lazy, this was much more fun, and I don't have time to run through their docs.

Comments
Contact Chris SchofieldBlogCFC was created by Raymond Camden. This blog is running version 5.9.001.