Un-bloat CSS by using multiple classes
Let’s say you need six different 100px square boxes with different characteristics:
- Red with Border
- Blue with Border
- Green with Border
- Red without Border
- Blue without Border
- Green without Border

You COULD create a unique class for each of these, like so:
.redwithborder {
width: 100px;
height: 100px;
margin: 10px;
float: left;
background-color: red;
border: 3px solid black;
}
.bluewithborder {
width: 100px;
height: 100px;
margin: 10px;
float: left;
background-color: blue;
border: 3px solid black;
}
...etcBUT that’s called CSS Bloat because it includes a bunch of unnecessary repetitive code. Instead, create just five classes with simple, identifiable names that each handle something very specific:
.box {
width: 100px;
height: 100px;
margin: 10px;
float: left;
}
.red {
background-color: red;
}
.blue {
background-color: blue;
}
.green {
background-color: green;
}
.border {
border: 3px solid black;
}In your HTML, things look just as clean, just put a space between each of the classes you wish to apply to the div:
<div class="red border box">
</div>
<div class="blue border box">
</div>
<div class="green border box">
</div>
<div class="red box">
</div>
<div class="blue box">
</div>
<div class="green box">
</div>This method allows better future flexibility as well. If you wanted to create an orange box, or even a box with a background-image or some completely separate characteristic, you could. And then adding a border to that new box is simple adding a space and the “border” class name.
Does really IE6 or below support multiple classes? I’m not sure of it. Anyone could answer?
IE 6 does support multiple classes. Ryan Brill has a good explanation of it.
Basically, if you want to declare in your CSS #div.box.featured {
# background-color: #f5fbea;} IE 6 would not understand “box” and would apply the style to any div with the class “featured” not just divs with the class “box” and “featured”. Somewhat of a limitation but really no big deal.
Does not ie6 allow classes and ids though??
If so you could do red, green etc as a id (if only used once)
IE6 does support both classes and IDs. That is a good idea to separate them like that. Personally I would reserve ID’s for very unique things that you know you are only going to use once on a page, like a footer, for example.