CSS Tip: Selecting an Element that has Two Classes

If you’re familiar with CSS, you know that you define the style for an element with a specific class by referencing .className{ } in a style sheet and you’re familiar with the hierarchy of selectors, but did you know that there’s a selector that looks for an element with two classes?

Here’s an example page with three div tags. The first one has class1, the second one has class2 and the third one has both class1 and class2.

<div class="class1">This is div 1</div>
<div class="class2">This is div 2</div>
<div class="class1 class2">This is div 3</div>

Here’s a simple style sheet that, when included on the page, will set the font color of class1 and class2:

.class1 {

.class2 {

Here is the result:

The first div gets the red font because it has class1 assigned. The second div gets the green font because it has class2 assigned. The third div also gets the green font because class2 is the last class assigned to it, so it picks up the style from that class (when it conflicts with any style set by the first class).

Now, let’s say I want to make the third div’s font blue (without changing the style of the first two). I can’t change the class1 or class2 styles because that will change one of the other divs.

Fortunately, there’s a CSS selector that allows you to specify a style that applies to an element that has two classes. Just specify them as .class1.class2 with no space between the two class names.

This css entry will do the trick in the sample shown above:

.class1.class2 {

This uniquely identifies the third div because it has both of those classes.


Of course, this is an overly simplistic example, but I’ve had a few cases recently where this was helpful when working with objects that have multiple class names assigned by XPages and dojo.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: