Wednesday, February 24, 2010

Multiple CSS classes on the same element

You have an HTML element with two or more classes in the class name, something like "class1 class2" (separated by space and not by comma as some sites wrongly suggest) and some of the rules in the two classes overlap. What is order in which rules are read and do they overwrite other rules that are already in place?

I made a test HTML and I noticed that the rules in class2 overwrote the ones in class1, but since I had asked the wrong question, I had the wrong answer. If I changed the class name to "class2 class1" the result was the same!

It appears that the rules in CSS classes that overlap are overwritten based on their order in the document and latest win, overwriting the previous. In other words, if class1 would be defined later than class2, then its properties would overwrite class2's. The order of classes in a class name is complete without relevance!