CSS: multiple classes

CSS classes can actually be combined together on the same element to get interesting results due to the cascade. As I said in an earlier post, CSS classes can be used to create cumulative styles, thus resulting in a more flexible and reusable code.

For example, suppose that you have some floated images. You want that some of these images show a doubled border and in this case there are two classes that can be joined together:

.alignleft {
  float: left;
  margin-right: 5px;

.picture {
    padding: 5px;
    border: 5px double #aaa;

Then you add the above classes on an img element, like so:

<img src="pic.gif" alt="Picture" class="alignleft picture" />

However, there are a few things to keep in mind when using a solution like this. First, you should always specify style rules that don't conflict with each other. If you don't do so, then the cascading rules will decide what rule is the winner (e.g. when a class comes first or later in the source or when a rule is followed by an !important statement). Second, Internet Explorer 6 has a really poor support to multiple classes, so it's sometimes very difficult to select an element with two or more classes applied to it.

Anyway, if you aren't really worried about these issues, then multiple classes can actually be a useful way to apply styles in an elegant, reusable and semantic way.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

One thought on “CSS: multiple classes”

  1. I often use multiple classes and I remember that when just born the old (and useful before jQuery become so powerful) getElementsByClassName() function was not able to find elements with multiple classes.
    I didn't remember if the first one to publish it was Peter-Paul Koch, but surely Robert Nyman was the one who first publish a version capable of this even if I before of him wrote (and used) another workig version but never published. :P

    Now GetElementsByClassName() is native in most modern browsers and I hope that the time when we can forget IE6 will come ASAP!

    I'm not yet decided to drop IE6 support but just stopped to develop advanced function for it.
    I.E. I don't want to be my pages heavy-weighted by png-fix script or every kind of IE6 hacks/workaround/damned-headache! :)

    I prefer to use conditional comments and, in the case of multiple class... well, IE6 will have what it deserve... :)

    Once on perishablepress blog I suggested even to crash IE6 users'browser (just kidding!) or just serving a css-naked/scriptless (read: only textual) webpages.

    I'm not so sure that is not a good idea, yet!

    Happy life!

Leave a Reply

Note: Only a member of this blog may post a comment.