Coding with Jesse

Multiple classes in Internet Explorer

January 16th, 2006

I recently discovered the power of using multiple classes. That is, using more than one class on a single element. The class attribute simply accepts multiple classes separated by a space. For example, you can do something like this:

<style>
.box { border: 1px solid black; }
.small { width: 400px; }
.large { width: 800px; }
</style>

<div class="small box">
<div class="large box">

This is a great way to organize your CSS. For example, you can have a set of classes to define font styles and another set of classes to define box sizes. Then you can use them together in different combinations.

The class names "small" and "large" aren't totally clear, since they refer specifically to small and large box sizes. It'd be great if I could write "large title" and have it affect the font size instead of the width. So, I tried to change the definition by combining multiple classes in a single selector:

.box { border: 1px solid black; }
.box.small { width: 400px; }
.box.large { width: 800px; }

.title { color: blue; font-family: Arial; }
.title.small { font-size: 10px; }
.title.large { font-size: 20px; }

When I tried this in Firefox, everything worked great. Unfortunately, Internet Explorer doesn't support this. In fact, Internet Explorer will just look at the last class in the list. So, it will interpret the last example as if we had written this:

.box { border: 1px solid black; }
.small { width: 400px; }
.large { width: 800px; }

.title { color: blue; font-family: Arial; }
.small { font-size: 10px; }
.large { font-size: 20px; }

Small boxes will have small fonts, large boxes will have large fonts, small titles will be 400px wide, large titles will be 800px wide. Very unfortunate.

Once again, Internet Explorer ruins all the fun. Well, there's an up side to this. When we use "small" to affect the width in one place, and the font size in another place, we make it harder to understand and maintain the CSS. And isn't that supposed to be the point of using CSS?

Besides, not all is lost. We just have to come up with better names. We can still do this:

.border { border: 1px solid black; }
.small-box { width: 400px; }
.large-box { width: 800px; }

.title { color: blue; font-family: Arial; }
.small-text { font-size: 10px; }
.large-text { font-size: 20px; }

It sure isn't as pretty to write something like class="border small-box". But at least then we can use our "small-box" class in places that don't have borders, or use the "border" class to give a border to something without a fixed width.

In conclusion, avoid the .class1.class2 syntax altogether. It's not supported by Internet Explorer, and it makes code harder to read and manage. However, using multiple classes is completely supported and will make your CSS cleaner and more reusable.