10

In my css file is .a.b different than .a .b?

It's a simple question but it's always annoyed me. I tried it, but figured I would post it here in case this was useful as a reference.

Matt
  • 25,943
  • 66
  • 198
  • 303

3 Answers3

26

In my css file is .a.b different than .a .b?

Yes

.a.b is one or more elements with both classes.

<div class="a b">(target)</div>

.a .b is one or more elements with class b with any parent element with class a

<div class="a"><div class="b">(target)</div></div>

or even

<div class="a">
  <div>
    <div>
      <div class="b">(target)</div>
   </div>
   <div class="b">(target)</div>
   <div class="b">(target)
     <div class="b">(target)</div></div>
  </div>
</div>

They are very different.

I chose the direction in the example .a .b from right to left as all .b elements are the ones that will be the target for the CCS.

Additionally you could even do div.a.b for my first example and div.a div.b for the second examples.

Relevant Articles:

https://www.smashingmagazine.com/2007/07/css-specificity-things-you-should-know/

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
  • 2
    ie. classes together means on the same element; classes space separated is descendant elements, left to right. – Orbling Sep 17 '13 at 19:30
  • That's really helpful, I searched whole https://developer.mozilla.org and didn't find the usage of .a.b, where did your figure it out? – Kyung Lee Dec 04 '17 at 15:16
  • 1
    @GlennPallad https://stackoverflow.com/questions/25105736/what-is-the-order-of-precedence-for-css is good for starters. – Erik Philips Dec 04 '17 at 17:08
  • Will .a.b be different from .b.a? I tested and I didn't find any difference. – Cloud Walker Mar 19 '21 at 22:42
  • 2
    @CloudWalker that would be exactly the same. You're stating any element with a class of `a` and a class of `b`. Order has no matter in that regard. Kind of like saying any person with 10 fingers and 10 toes, it the same as saying 10 toes and 10 fingers. – Erik Philips Mar 21 '21 at 22:06
4
  • .a.b means "an element with both class a and class b"

    Example:

    <div class="a b">(element)</div>
    
  • .a .b means "an element with class b for which either its parent or grand-parent or grand-grand-parent, etc, has class a"

    Examples:

    <div class="a">
      <div class="b">(element)</div>
    </div>
    
    <div class="a">
      <div class="c">
        <div class="b">(element)</div>
      </div>
    </div>
    
rid
  • 61,078
  • 31
  • 152
  • 193
2

YES! They are different!

.a.b is an element with both classes a and b

<span class="a b"></span>

.a .b is an element where a is the parent or higher of class b

<span class="a">
    <span class="b">
    </span>
</span>