tags:

views:

278

answers:

4

I need to style an element that has both class "a" and class "b". How do I do it?

The order the classes appear in the html might vary.

<style>
div.a ? div.b{
color:#f00;
}
</style>
<div class="a">text not red</div>
<div class="b">text not red</div>
<div class="a b">red text</div>
<div class="b a">red text</div>
A: 

Yeah, use a common class, or why not, JavaScript if the content changes dynamically

cyborg_ar
+11  A: 

That's entirely possible.

div.a   {color:blue;}
div.b   {color:green;}
div.a.b {color:red;}

If you specify two classes on an element (without any spaces), that means that it must have both for the rule to apply.

bdukes
+1 with a note it's not supported in IE6
Van Gale
+2  A: 

Class selectors can be combined:

div.a.b {
  color: red;
}

Quoting from the spec:

To match a subset of "class" values, each value must be preceded by a ".".

For example, the following rule matches any P element whose "class" attribute has been assigned a list of space-separated values that includes "pastoral" and "marine":

p.marine.pastoral { color: green }

This rule matches when class="pastoral blue aqua marine" but does not match for class="pastoral blue".

Rob Kennedy
A: 
div[class~="a"][class~="b"]{
color:#f00;
}
Claudio