limonte limonte - 15 days ago 6
CSS Question

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

Could someone explain to me why CSS > sign (direct child) overrides the default color of all

<li>
tags in this example:



ul > li {
color:red;
}

<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>





Expected result:



enter image description here

Actual result:



enter image description here

I know that I can fix it by adding
li { color: black; }
, but I'm wondering why
ul > li
overring the default color for
<li>
?

Answer

The issue is not the child combinator (>), it's the color property, which is inheritable. This means that a given element takes the style of the parent. Try this instead:

ul > li {
  color: red;
}
ul > 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: