CSS / HTML 子级会覆盖父级吗?
给定以下代码:
<div id="bla">
<p class="blubber">Johnny Bananas</p>
</div>
以及该 html 文档 head 中的样式:
<style>
div#bla{background:yellow}
p.blubber{background:purple}
</style>
为什么子级将被着色为紫色并覆盖其父级?
Given the following code:
<div id="bla">
<p class="blubber">Johnny Bananas</p>
</div>
and the style in head of that html doc:
<style>
div#bla{background:yellow}
p.blubber{background:purple}
</style>
Why is it that the child will be coloured purple and overlay its parent?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
默认情况下,子级不会继承
background
属性。因此,div#bla
的背景样式不适用于p.blubber
,并且p.blubber
可以独立地指定自己的背景颜色。它的父级,无论特殊性如何。由于
background
未被继承,因此实际上不会发生覆盖。The
background
property is not inherited by children by default. Therefore, the background style ofdiv#bla
does not apply top.blubber
, andp.blubber
can specify its own background color independently of its parent and regardless of specificity.And since
background
isn't being inherited, no overriding actually takes place.当使用多个样式表时,样式表可能会争夺对特定选择器的控制权。在这些情况下,必须有一些规则来确定哪种样式表的规则将胜出。以下特征将决定矛盾样式表的结果。
查看有关级联顺序的部分 - http://htmlhelp.com/reference/css/struction.html
When multiple style sheets are used, the style sheets may fight over control of a particular selector. In these situations, there must be rules as to which style sheet's rule will win out. The following characteristics will determine the outcome of contradictory style sheets.
check out the section on cascading order - http://htmlhelp.com/reference/css/structure.html
由于特异性相同,因此该规则将应用于
p
元素。如果删除p
并只有.blubber
,则它将无法工作。此外,子级不能覆盖父级,因此如果有更多内容,您会在
p
周围看到黄色(向div
添加填充)。背景颜色不是CSS中的继承属性。
Because the specificity is the same, so the rule will apply to the
p
element. If you remove thep
and just have.blubber
, it wouldn't work.Also, children can't override parents, so if there were more content, you'd see yellow around the
p
(add padding to thediv
).Background color is not and inherited attribute in CSS.