2

在片段上,第 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>

4

2 回答 2

4

那是因为一些 CSS 属性是可继承的:

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

某些属性是继承属性,如其属性定义表中所定义。这意味着,除非级联产生一个值,否则该值将由继承确定。

在这种情况下,两者colortext-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>

于 2016-03-05T00:36:48.707 回答
2

它没有传播,因为他们没有设置,所以他们的孩子.a>div继承styles了他们的。parentcolortext-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>

于 2016-03-05T00:36:14.580 回答