CSS selector for an element having class .a and cl

2019-03-11 21:44发布

问题:

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>

回答1:

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

div.a {
  color: blue;
}
div.b {
  color: green;
}
div.a.b {
  color: red;
}
<div class="a">
  A
</div>
<div class="b">
  B
</div>
<div class="a b">
  AB
</div>



回答2:

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".



回答3:

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


回答4:

/* select div tag having class a and b together */

 <style>
    div.a.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>


回答5:

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