csscss-cascade

Why direct child selector is propagating?


On the snippet, the 3rd h2 should not be affected by the css, so why it is?

.a > div { color: blue; text-align: center; }
<div class="a">
    <h2>Title</h2>
    <div>
        <h2>this shoud be center and blue</h2>
        <div>
            <h2>this should Not be center or blue</h2>
        </div>
    </div>
</div>


Solution

  • That's because some CSS properties are inheritable:

    Inheritance propagates property values from parent elements to their children. The inherited value of a property on an element is the computed value of the property on the element’s parent element. [...]

    Some properties are inherited properties, as defined in their property definition table. This means that, unless the cascade results in a value, the value will be determined by inheritance.

    In this case, both color and text-align are inheritable. If you don't want that element to inherit those properties, you can provide some value in the cascading. For example, you can set these properties to their initial value, via the initial keyword:

    .a div { /* Set initial values to all descendants */
      color: initial;
      text-align: initial;
    }
    .a > div { /* Set desired values to children */
      color: blue;
      text-align: center;
    }
    <div class="a">
      <h2>Title</h2>
      <div>
        <h2>this shoud be center and blue</h2>
        <div>
          <h2>this should Not be center or blue</h2>
        </div>
      </div>
    </div>