Can you customize an element using CSS only if 2 classes are present?

As you probably already know, you can have several classes on elements separated by a space.

Example

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

And with CSS, you can target the div to .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> 

What CSS selector would I use to get only the first div (suppose I can't use .content:first-child or the like)?

+64
css css-selectors
Mar 13 '09 at 0:18
source share
2 answers

Yes, just connect them: .content.main . See CSS Class Selector .

But keep in mind that Internet Explorer prior to version 6 does not support multiple class selectors and simply distinguishes the last class name.

+99
Mar 13 '09 at 0:20
source share

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

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

Or:

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

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

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

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

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

Since IE6 does not support multiple classes, we cannot use .content.main , but there are some javascript libraries, such as IE-7.js , that activate the attribute selector, but still seem unsuccessful when it comes to multiple classes. I tested this workaround in IE6 with javascript allowing an attribute selector and it is ugly, but it works.

I have yet to find a script that forces IE6 to support multiple class selectors, but has found many that allow attribute selectors. If anyone knows what works, please give me a shout in the comments so I can get rid of this workaround.

+9
Aug 21 2018-11-11T00:
source share



All Articles