1

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.

2
  • To clarify, are you attempting to select ("Red"), or ("Blue","Green")? Commented Oct 9, 2013 at 21:15
  • @caleb.breckon I want to select Red Commented Oct 9, 2013 at 21:16

6 Answers 6

5

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.

2

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

h2.first.second

2

I have created a working CodePen example of the solution.

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

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
1

You can select

.first.second {}

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

1

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.