Почему прямой дочерний селектор распространяется?

На фрагменте 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>

2 ответа

Решение

Это потому, что некоторые свойства CSS наследуются:

Наследование распространяет значения свойств от родительских элементов к их дочерним элементам. Унаследованным значением свойства элемента является вычисленное значение свойства родительского элемента элемента. [...]

Некоторые свойства являются унаследованными свойствами, как определено в их таблице определения свойств. Это означает, что, если каскад не приводит к значению, значение будет определяться наследованием.

В этом случае оба color а также text-align наследуются Если вы не хотите, чтобы этот элемент наследовал эти свойства, вы можете указать какое-либо значение в каскадировании. Например, вы можете установить эти свойства к их начальному значению через initial ключевое слово:

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

Это не размножение, дети .a>div наследуют styles от их parent, так как они не имеют 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>

Другие вопросы по тегам