CSS Specificity and Inheritance(CSS 特性和继承)
问题描述
给定以下代码:
* {
font-size: 18px;
}
.container {
font-size: 50%;
}
<div class="container">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cupiditate explicabo fugiat laborum minus ullam? Amet delectus facilis id quam temporibus.
</p>
</div>
结果是 <p>
标签应用了 18px 字体大小.但是不应该 div 容器内的每个元素都继承我应用的字体大小吗?无论 *
选择器如何将字体大小应用于 <p>
标记,因为一个tag只值1分,而class值10分?
The result is that the <p>
tag has 18px font-size applied.
But shouldn't every element that is inside of the div container inherit the font-size I apply to it?
Regardless of the *
selector applying the font-size to the <p>
tag,
because a tag is only worth 1 point and a class is worth 10 points?
推荐答案
.container
规则与 p
元素不匹配.因此,特异性在这里无关紧要.继承和特殊性是独立的概念,它们交互的唯一时间是更具体/不太具体的规则包含带有 inherit
的声明.这里不是这样.
The .container
rule doesn't match the p
element. So specificity is irrelevant here. Inheritance and specificity are separate concepts and the only time they interact is when more specific/less specific rules contain declarations with inherit
. That is not the case here.
就p
元素而言,只有*
规则适用,*
包含自己的font-size
声明,因此指定的字体大小遵循该声明.
As far as the p
element is concerned, only the *
rule applies, and the *
contains its own font-size
declaration, and so the specified font size follows that declaration.
如果 *
规则没有自己的 font-size
声明,则 p
元素将继承自 .container
.
If the *
rule didn't have its own font-size
declaration, then the p
element would inherit from .container
.
如果您希望 .container
的后代采用其字体大小,则需要一个额外的 .container *
规则.非常小心 inherit
关键字在涉及相对值时 - 你可能打算保持所有后代的大小相同,所以 1em
或 100%
在这里比 inherit
更合适:
If you want descendants of .container
to take after its font size, you will need an additional .container *
rule. Be very careful with the inherit
keyword when it comes to relative values, though — you probably meant to keep all descendants the same size, so 1em
or 100%
is more appropriate here than inherit
:
* {
font-size: 18px;
}
.container {
font-size: 50%;
}
.container * {
font-size: 1em;
}
<div class="container">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cupiditate explicabo fugiat laborum minus ullam? Amet delectus facilis id quam temporibus.
</p>
</div>
这篇关于CSS 特性和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!