Optimize Your CSS by Combining Classes

This is one of the more useful CSS techniques I’ve learned, and seeing as I picked it up somewhat later than I would have liked, I’m sure there are others who are not simplifying their CSS by breaking it up in this way.

In a nutshell, CSS allows you to assign multiple classes to a particular element. For example you can apply a border to an image and float it to the right using two separate classes:

HTML:

<img class="border right" src="image.jpg" alt="alt" />

CSS:

.border {
border: 1px solid #999;
}
.right {
float: right;
}

If you wanted to float the image to the left, you would just create a .left class and use that instead:

HTML:

< img class="border left" src="image.jpg" alt="alt" />

CSS:

.left {
float: left;
}

Easy, huh? Plus, if you are straight forward with your CSS naming conventions you can actually remember what class does what. Bonus!

The ‘Other’ Method

The alternative to this technique is to create separate classes for each element that is styled differently. So, the above example would now become the following:

HTML (image floated to the left):

<img class="leftborder" src="image.jpg" alt="alt" />

HTML (image floated to the right):

<img class="rightborder" src="image.jpg" />

CSS (for both):

.leftborder, .rightborder {
border: 1px solid #999;
}
.leftborder {
float: left:
}
.rightborder {
float: right;
}

However, this technique seems less elegant to me and means that you are likely to end up creating more individual classes, which ultimately makes it harder to keep track of all your styles.

It’s always best to avoid ‘classitis’ whenever you can – you’ll thank yourself when you have to go back to a site in the future to make updates.

A Final Word

A further advantage of combining classes is that you can use that class for multiple elements. So, if you want to float anything else over to the right (such as a div), all you have to do is use the .right class along with any other styles you wish to apply to the element.

I often find this technique useful for floating things like images, divs and blockquotes within content and for playing around with borders.

You don’t have to limit yourself to combining two classes either. Dan Cederholm talks about how he assigns three classes to an image in this post.