"Target"
"NotMyTarget"

How to select a div with class "A", but NOT with class "B"?

I have divs:

<div class="A">"Target"</div> <div class="AB">"NotMyTarget"</div> <div class="AC">"NotMyTarget"</div> <div class="AD">"NotMyTarget"</div> <div class="AE">"NotMyTarget"</div> 

Is there a CSS selector that will get me a div containing Target but not divs containing NotMyTarget ?

The solution should work on IE7, IE8, Safari, Chrome and Firefox.

Edit: So far, Nick is close. This is awkward and I don't like the solution, but at least it works:

 .A { /* style that all divs will take */ } div.B { /* style that will override style .A */ } 
+45
css css-selectors
Mar 20 2018-10-10T00:
source share
3 answers

You can use an attribute selector to match a div that has only one class:

 div[class=A] { background: 1px solid #0f0; } 

If you want to select another div that has multiple classes, use quotation marks:

 div[class="AC"] { background: 1px solid #00f; } 

Some browsers do not support attribute selector syntax. As usual, โ€œsome browsersโ€ is a euphemism for IE 6 and later.

See also: http://www.quirksmode.org/css/selector_attribute.html

Full example:

 <!DOCTYPE html> <html> <head> <style> .A { font-size:22px; } .B { font-weight: bold; border: 1px solid blue; } .C { color: green; } div[class="A"] { border: 1px solid red; } div[class="AB"] { border: 3px solid green; } </style> </head> <body> <div class="A">"Target"</div> <div class="AB">"NotMyTarget"</div> <div class="AC">"NotMyTarget"</div> <div class="AD">"NotMyTarget"</div> <div class="AE">"NotMyTarget"</div> </body> </html> 

EDIT 2014-02-21: Four years later :not now widely available, although detailed in this particular case:

 .A:not(.B):not(.C):not(.D):not(.E) { border: 1px solid red; } 

Unfortunately, this does not work in IE 7-8, as stated in the question: http://caniuse.com/#search=:not

+34
Mar 20 '10 at 3:18
source share
 .A:not(.B) {} 

But guess who does not support this ... Indeed, IE <= 8.

+21
Mar 20 '10 at 9:07
source share

I think the best thing you can do (until CSS 3) is to override the styles in this case with what you don't want from the class AB to A , for example:

 .AB { /* Styles */ } .A { /* Reverse any styling you don't want */ } 
+15
Mar 20 '10 at 1:02
source share



All Articles