Skip to content Skip to sidebar Skip to footer

Specificity Of Nested CSS Selectors

I am trying to figure out why 'Item One' does not show as orange, below. According to specificity rules, the selector .one.two, should have a specificity score of 20 (two classes).

Solution 1:

So it feels like it should show as orange, not blue.

Any idea why it doesn't?

Your ul is orange. But your li is colored blue independently of the color of its parent because you have explicitly targeted it and applied a color to it. It will not inherit its parent's color if you override the implicit color: inherit.

why can't I have a space between the .one and the .two in the .one.two selector?

Because that's a completely different selector. .one .two matches a .two inside a .one. .one.two (with no space) matches an element that is both .one and .two.

<div class="one">
  <div class="two"></div> /* matched by .one .two */
</div>

<div class="one two"></div> /* matched by .one.two */

Solution 2:

Your css is working fine but there is also this css

.one li {
  color: blue;
}

So your css is applying orange color on .one.two but .one li css overlapping and showing blue color.

You can add this css if you want orange color on li under .one.two

.one.two li {
  color: orange;
}

Solution 3:

Just you need to add li in the selector after .one.two

<!DOCTYPE html>
<html>

<head>
  <style>
    .one {
      color: red;
    }
    .two {
      color: green;
    }
    .one li {
      color: blue;
    }
    .one.two li {
      color: orange;
    }
  </style>
</head>

<body>
  <div>
    <ul class="one two">
      <li>Item One</li>
    </ul>
  </div>
</body>

</html>

Post a Comment for "Specificity Of Nested CSS Selectors"