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

时间:2016-03-05 00:27:47

标签: css css-cascade

在代码段上,第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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:4)

那是因为一些CSS属性是inheritable

  

继承将属性值从父元素传播到其子元素。元素上属性的继承值是   计算元素父元素的属性值。 [...]

     

某些属性是继承属性,如其中所定义   属性定义表。这意味着,除非级联结果   在值中,该值将由继承确定。

在这种情况下,colortext-align都是可继承的。如果您不希望该元素继承这些属性,则可以在级联中提供一些值。例如,您可以通过initial value

将这些属性设置为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>

答案 1 :(得分:2)

它没有传播,.a>div的孩子从他们的styles继承parent,因为他们没有设置colortext-align

enter image description here

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