Categories
css css-selectors

What does a space mean in a CSS selector? i.e. What is the difference between .classA.classB and .classA .classB?

133

What is the difference between these two selectors?

.classA.classB {
  border: 1px solid;
}

.classA .classB {
  border: 1px solid;
}

    60

    A style like this is far more common, and would target any type of element of class “classB” that is nested inside any type of element of class “classA”.

    .classA .classB {
      border: 1px solid; }
    

    It would work, for example, on:

    <div class="classA">
      <p class="classB">asdf</p>
    </div>
    

    This one, however, targets any type of element that is both class “classA”, as well as class “classB”. This type of style is less frequently seen, but still useful in some circumstances.

    .classA.classB {
      border: 1px solid; }
    

    This would apply to this example:

    <p class="classA classB">asdf</p>
    

    However, it would have no effect on the following:

    <p class="classA">fail</p>
    <p class="classB">fail</p>
    

    (Note that when an HTML element has multiple classes, they are separated by spaces.)

    1

    • 3

      Showing the failed case is helpful.

      – Hal50000

      Oct 23, 2016 at 15:44

    2

    .classA.classB it means that the elements with both classes name will be selected whereas .classA .classB means that the element with class name classB inside the classA will only be selected.

    1

    • 6

      This is correct, but the question was already answered correctly a decade ago; it didn’t really need a new answer.

      – Brilliand

      Jul 27, 2020 at 21:21