90

As you probably already know, you may have multiple classes on elements separated by a space.

Example

<div class="content main"></div>

And with CSS you can target that div with either .content or .main. Is there a way to target it if and only if both classes are present?

Example

<div class="content main">I want this div</div>
<div class="content">I don't care about this one</div>
<div class="main">I don't want this</div>

Which CSS selector would I use to get the first div only (assume I can't use .content:first-child or similar)?

Community
  • 1
  • 1
alex
  • 479,566
  • 201
  • 878
  • 984

2 Answers2

147

Yes, just concatenate them: .content.main. See CSS class selector.

But note that the Internet Explorer up to version 6 doesn’t support multiple class selectors and just honors the last class name.

Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • As long as that's 'up to' and not 'inclusive of' IE6 :) – alex Mar 13 '09 at 00:34
  • No, IE6 doesn't correctly understand chained CSS selectors. That rule will apply to *all* elements with class="main" regardless of whether they are class="content" too – Gareth Mar 13 '09 at 00:49
  • An illustration for IE6 vs other browsers for anyone who cares: http://stackoverflow.com/questions/3772290/css-selector-that-applies-to-elements-with-two-classes – BoltClock Aug 21 '11 at 05:29
12

Just for the sake of it (I don't really recommend you do this), there is another way to do it:

.content[class~="main"] {}

Or:

.main[class~="content"] {}

Reference: http://www.w3.org/TR/CSS2/selector.html

E[foo~="warning"] Matches any E element whose "foo" attribute value is a list of space-separated values, one of which is exactly equal to "warning"

Demo: http://jsfiddle.net/eXrSg/

Why this is actually useful (for IE6 at least):

Since IE6 does not support multiple classes, we can't use .content.main, but there are some javascript libraries like IE-7.js that enable the attribute selector, but still seem to fail when it comes to multiple classes. I have tested this workaround in IE6 with javascript enabling the attribute selector, and it is ugly, but it works.

I have yet to find a script that makes IE6 support multiple class selectors but have found many that enable attribute selectors. If someone knows of one that works, please give me a shout in the comments so I can be rid of this workaround.

Wesley Murch
  • 101,186
  • 37
  • 194
  • 228