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>

_config.yml

Playground

Try out the code in the following playground.

So what’s the difference?

  • .a.b applies on all elements with the class a and b applied to them.
  • Where as .a .b (with a space) applies to elements where b is a descendant of a (any descendant). A space is a descendant selector.
Written on January 28, 2025