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>
To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class.
An element is usually only assigned one class. The corresponding CSS for that particular class defines the appearance properties for that class. However, we can also assign multiple classes to the same element in CSS. In some cases, assigning multiple classes makes page styling easier and much more flexible.
class selector can also be used to select multiple classes.
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>
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 forclass="pastoral blue"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With