97

What is the different between .class.class and .class .class?

2
  • 7
    The first selects the element which has both classes. The latter select an element which has the class class which has a parent which has the class class
    – PeeHaa
    Commented Jun 30, 2013 at 14:30
  • 2
    In order to make everything more understandable I think it would be better to distinguish the classes in class1 and class2
    – Davide
    Commented Jul 22, 2019 at 14:01

5 Answers 5

134

.class .class matches any elements of class .class that are descendants of another element with the class .class.

.class.class matches any element with both classes.

3
  • 4
    For the latter, does the order matter? Commented Jan 16, 2016 at 0:11
  • 5
    @ClarusDignus , in case of .class.class, order doesn't matter. Here is fiddle. Commented Sep 28, 2016 at 8:58
  • @NoopurDabhi Understood. Thanks for the example. Commented Sep 28, 2016 at 16:09
97
  1. .name1.name2

    means a div or an element having both classes together, for example:

    <div class="name1 name2">...</div>
    

  1. .name1 .name2

    means a div or an element which has a class name1 and any of its child nodes having class name2

    <div class="name1">
        <div class="name2">
            ...
        </div>
    </div>
    
23
.class1.class2

Element that has both class1 and class2 set within it's class attribute (like that: class="class1 class2")

.class1 .class2

Element with class2 that is a descendant of an element with class1 class

3
  • 3
    This is the most understandable answer, IMO.
    – nbro
    Commented Jul 20, 2015 at 22:01
  • Yet I can't even read it without getting confused lol and im a webdev
    – brandito
    Commented Mar 27, 2018 at 1:52
  • @nbro no, this is more easy to understand stackoverflow.com/a/17391614/8618055 Commented Dec 16, 2019 at 5:04
4

.class.class can also be used to avoid the use of !important in case that a higher specificity selector prevents your rule from being applied.

In this case there are not two classes in the HTML element. You only repeat the class which specificity you want to increase in the style (selector), like

(HTML) <div class="something">...</div>

(CSS) .something.something {}
1

.class1.class2: Selects all elements with class2 that is a descendant of an element with class1

.class1 .class2: Selects all elements with both class1 and class2 set within its class attribute

Lets see with code example:

.class1.class2{
  color: red;
}

.class1 .class2{
  color: blue;
}
<div class="class1 class2">
  Hi I am ".class1.class2" selector
</div>

<div class="class1">
  <p class="class2">
    Hi I am ".class1 .class2" selector
  </p>
</div>

Jsfiddle link for better ref: https://jsfiddle.net/srikrushna_pal/16dw3n0u/3/

Not the answer you're looking for? Browse other questions tagged or ask your own question.