为什么直接子选择器传播?

Why direct child selector is propagating?

在代码段中,第 3 个 h2 不应受到 css 的影响,为什么会这样?

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

它没有传播,.a>div 的 children 正在从他们的 parent 继承 styles,因为他们没有 color 并且text-align设置。

.a > div {
  color: blue;
  text-align: center;
}
div {
  color: black;
  text-align: left;
}
<div class="a">

  <h2>London 1</h2>
  <p>London is the capital city of England. It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.</p>

  <div class="">


    <h2>this shoud be center and blue</h2>
    <p>London is the capital city of England. It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.</p>

    <div class="">
      <h2>this should Not be center or blue</h2>
      <p>London is the capital city of England. It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.</p>
    </div>


  </div>



</div>

那是因为一些 CSS 属性是 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.

在这种情况下,colortext-align都是可继承的。如果您不希望该元素继承这些属性,您可以在级联中提供一些值。例如,您可以将这些属性设置为它们的 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>