CSS特殊性和继承 [英] CSS Specificity and Inheritance
问题描述
给出以下代码:
* {
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>
标记,
是因为标记仅值1点,而类则值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
元素不匹配。因此,此处的特异性无关紧要。继承和特殊性是不同的概念,只有在更具体/较不具体的规则包含带有继承
的声明时,它们才相互作用。
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
将从继承。容器
。
If the *
rule didn't have its own font-size
declaration, then the p
element would inherit from .container
.
如果您希望 .container
的后代采用其字体大小,则需要附加的 .container *
规则。不过,在涉及相对值时,请非常小心使用 inherit
关键字-您可能要保持所有子代的大小相同,因此 1em
或 100%
在这里比继承
更合适:
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特殊性和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!