Search code examples
htmlcsscss-selectors

CSS Child Selector (>) not working with certain properties


When I tried to apply certain CSS properties to direct child of a parent element using ">", it works well with some of the properties like border, but not with font-properties like color, font-weight etc..

My HTML is

<ul>
  <li>Item 1</li>
  <li>
    <ol>
      <li>Subitem 2A</li>
      <li>Subitem 2B</li>
    </ol>
  </li>
</ul>

CASE1 CSS:

ul>li {
    color:#F00;
}

With the above CSS code, the color: #F00 property gets applied to all the li elements comes under the parent and its child. The expected was, it should be applied only to the direct child lis.

CASE 2 CSS:

ul>li {
  border: solid 1px #000;
}

The above code works as expected and the border gets applied only to the direct li child.

I know this can be fixed by overriding it with another class. But wanted to know the reason why some of those CSS properties are inherited to all levels of hierarchy and others not.


Solution

  • It's happening due to the default inheritance capability of certain CSS Properties. Values of these kind of properties will be transmitted to the child by default.

    This document from W3C gives detailed list of inheritance in various CSS properties. Full property table