Mohsen Safari
Mohsen Safari

Reputation: 6795

How can I select an element with two classes?

I have this HTML:

<h2 class="first second">Red</h2>
<h2 class="second">Blue</h2>
<h2 class="first">Green</h2>

How can I select h2 with first and second class?

thanks about answers


Update:

If I have another h2 tag like this:

<h2 class="first second third">Default</h2>

it will be red with h2.first.second selector. Is there any way to select only element with first and second classes, not more.

Upvotes: 1

Views: 149

Answers (6)

Mohsen Safari
Mohsen Safari

Reputation: 6795

The following rule matches any h2 element whose class attribute has been assigned a list of whitespace-separated values that includes both "first" and "second":

h2.first.second { color: red }

Reference

But, to select an element whose class attribute exactly equal "first" and "second" I used this rule:

h2[class="first second"], h2[class="second first"] { color: red }

JsFiddle demo.

Upvotes: 1

JeremyS
JeremyS

Reputation: 437

You can select

.first.second {}

if you want only the first h2 to be selected. Make sure there is no space!

Upvotes: 1

Ryan
Ryan

Reputation: 3926

To select elements that have multiple classes simple use this:

h2.first.second

Note that there is no space between the classes, as apposed to the following which would select elements with the class of second which are inside a h2 element with the class of first

h2.first .second

Upvotes: 2

Adam
Adam

Reputation: 5236

I have created a working CodePen example of the solution.

h2.first.second {
/* styles go here*/
}

Upvotes: 2

aarryy
aarryy

Reputation: 502

If you are trying to select h2 with first and second class simutaneously

h2.first.second

Upvotes: 2

James Donnelly
James Donnelly

Reputation: 128771

Simply:

h2.first.second {
    color: red;
}

This selects the h2 element with both classes "first" and "second". Refer to the CSS Selectors Level 3 W3 recommendation for more info.

JSFiddle demo.

Upvotes: 5

Related Questions