在代码段上,第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;
答案 0 :(得分:4)
那是因为一些CSS属性是inheritable:
继承将属性值从父元素传播到其子元素。元素上属性的继承值是 计算元素父元素的属性值。 [...]
某些属性是继承属性,如其中所定义 属性定义表。这意味着,除非级联结果 在值中,该值将由继承确定。
在这种情况下,color
和text-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
,因为他们没有设置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>