Can you target an element with CSS only if 2 classes are present?

CssCss Selectors

Css Problem Overview


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)?

Css Solutions


Solution 1 - Css

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.

Solution 2 - Css

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionalexView Question on Stackoverflow
Solution 1 - CssGumboView Answer on Stackoverflow
Solution 2 - CssWesley MurchView Answer on Stackoverflow