Why CSS selector with > sign (direct child) overrides default styles?

The issue is not the child combinator (>), it’s the color property, which is inheritable.

Although the initial value of the color property varies from browser to browser, inherit is common. This means that an element’s text color is inherited from the parent. You’re seeing this in your code.

In contrast, the border property is not inheritable. Note how, unlike the text color, it applies only to your targeted li:

ul > li {
  color: red;
  border: 1px solid black;
}

li { border: 1px solid inherit !important; }
<ul>
  <li>This should be red
    <ol>
      <li>default color 1</li>
      <li>default color 2</li>
    </ol>
  </li>
  <li>And this should be red also
    <ol>
      <li>default color 3</li>
      <li>default color 4</li>
    </ol>
  </li>
</ul>

To achieve your styling objective, set a default color for the li element. This will override inherit. Here’s an example:

ul > li {
  color: red;
}
li {
  color: black;
}
<ul>
  <li>This should be red
    <ol>
      <li>default color 1</li>
      <li>default color 2</li>
    </ol>
  </li>
  <li>And this should be red also
    <ol>
      <li>default color 3</li>
      <li>default color 4</li>
    </ol>
  </li>
</ul>

References:

  • 14.1 Foreground color: the color property
  • 6.2.1 The inherit value

Leave a Comment