CSS - To Space or Not to Space - What is the difference?
What is the difference between the following css selectors: .a.b
and .a .b
?
The latter has a space between the selectors, but the former does not.
.a.b {
background-color: red;
}
.c .d {
background-color: yellow;
}
<div class="a b">
a.b selects something with both a and b
</div>
<div class="a">
class a - a.b selector does not apply
</div>
<div class="b">
class b - a.b selector does not apply
</div>
<div class="c d">
class c d (with a space) - this means d must be inside c. it doesn't apply here.
</div>
<div class="c">
<div class="d">
d is inside c - yellow background applies here
</div>
</div>
Playground
Try out the code in the following playground.
So what’s the difference?
.a.b
applies on all elements with the classa
andb
applied to them.- Where as
.a .b
(with a space) applies to elements whereb
is a descendant ofa
(any descendant). A space is a descendant selector.
Written on January 28, 2025