Multiple class CSS selector

This is a handy tip not many know about, yet it is very simple. When starting to learn CSS you learn about classes and how you can use many classes on an HTML element. Here comes the cool part, you can also use CSS selectors to match an element with more than one class. Consider the following code:

<a href="#" class="toggle enabled" title="Toggle"></a>

With the following CSS:

.toggle{
display: block;
height: 20px;
width: 20px;
background: url(myimage.png);
}

Let's say you want to change the background image position depending on the state of the toggler. The state can be enabled or disabled or hidden. These are common class names so using a selector like .enabled is not very good practice. The solution is to look for both classes (e.g. toggle and enabled). You do this by writing both classes without a space in between. For example:

.toggle.enabled{
background-position: 0 0;
}
.toggle.disabled{
background-position: 0 -20px;
}
.toggle.hidden{
display: none;
}

This technique can prove very useful in many situations. Specially when styling dynamic content. Note that it also works with ids. For example the following selector matches an element with the id wonderwoman and the class plane:

#wonderwoman.plane{
visibility: hidden;
}

Rate this item
(0 votes)
Tagged under

2 comments

  • Comment Link Demente Wednesday, 16 November 2011 20:26 posted by Demente

    @Joel Strange. Did you double check and made sure it's not a cache issue?

  • Comment Link Joel Tuesday, 15 November 2011 22:26 posted by Joel

    Didn't work for me. FF7, Chrome nor IE9.

Leave a comment