Home > Software design >  CSS .class1.class2 not selecting as expected
CSS .class1.class2 not selecting as expected

Time:10-17

I wonder why an element has attributes of .class1 and .class2, but not .class1.class2. Please explain. If the parent has .class1 and the element has .class2, then the element is supposed to have both classes. It has, but can't be selected using .class1.class2. In contrast, if the parent has .class1 and .class2, the child will be selected using .class1.class2, no matter what their own class attribute is.

.class1 {
  background-color: lightgray;
}

.class2 {
  color: green;
}

.class1.class2 {
  font-weight: bold;
}
<div class=class1>
  <p class=class2>
    HAS BOTH .class1 and .class2, but NOT .class1.class2 !?!
  </p>
</div>

<div >
  <p>
    .class1.class2
  </p>
  <p class=class2>
    BUT here: .class1.class2
  </p>
  <p class=class1>
    AND HERE: .class1.class2
  </p>
  <p class=unknown>
    .class1.class2
  </p>
</div>

CodePudding user response:

.class1.class2 selects all elements that explicitly have both class names in the class attribute. The reason the first p tag in your example has both the .class1 and .class2 styles is because the styles from the parent element 'cascade' (Cascading Style Sheets, CSS) onto the child elements. The child element isn't selected by the parent's class names, but the styles cascade onto the child unless the child overwrites them. In the second example, the parent element is selected by .class1, .class2, and .class1.class2 since it has both classes, and those styles are passed down to the children.

CodePudding user response:

As the document here points out CSS Selector Reference

.class1.class2 - .name1.name2 - Selects all elements with both name1 and name2 set within its class attribute

and

.class1 .class2 - .name1 .name2 - Selects all elements with name2 that is a descendant of an element with name1

The reason you get font-weight: bold; on the below HTML block is because the <p> tag inherit the style from its parent which it .class1.class2 { font-weight: bold }

<div >
   <p class=class2>
      BUT here: .class1.class2
   </p>
   <p class=class1>
    AND HERE: .class1.class2
   </p>  <p class=unknown>
    .class1.class2
   </p>
</div>
  •  Tags:  
  • css
  • Related