CSS: multiple class selectors

With the recent discussion of CSS style rules and quirks, I thought I’d mention one of my favorite CSS features that I’ve been making a lot of use of recently: multiple class selectors.

This is one CSS2 addition that isn’t mentioned much in CSS books (at least that I’ve seen), although most recent browsers do support it - all the “good” ones and IE, too. :)

According to the specification, you can apply multiple class attributes to any element, separated by spaces, such as:
<h1 class="title special">Test</h1>, which is useful, because then you can have separate rule definitions for title and special which you can share with any other elements on the page. If you think about it, this can serve to dramatically reduce duplication in your style sheets.

In addition, you can specify rules that only apply to elements where both classes are specified, for further control & flexibility.

So, for example, here is some code that demonstrates this:

[HTML & CSS]
<style>
.title { font-size: 40px; }
.colored { color: red; }
.special { font-style: italic; }
.special.colored { font-weight: bold; }
</style>

<h1 class="title colored">Test</h1>
<p>This is a test of multiple class selectors.</p>
<p>The H1 element above would be red and have a font size of 40px.</p>
<p class=”colored”>This paragraph would be colored red.</p>
<p class=”special”>This paragraph would be italicized.</p>
<p class=”special colored”>This paragraph would be italicized, colored red, and bold.</p>

The above would produce the following display:

Test

This is a test of multiple class selectors.

The H1 element above would be red and have a font size of 40px.

This paragraph would be colored red.

This paragraph would be italicized.

This paragraph would be italicized, colored red, and bold.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*