我正在阅读CSS Spec 2.1并得到了这个问题。
关于继承,它说:
When inheritance occurs, elements inherit computed values. The computed value from the parent element becomes both the specified value and the computed value on the child.
但是对于属性的继承
值,它表示:
Each property may also have a cascaded value of 'inherit', which means that, for a given element, the property takes the same specified value as the property for the element's parent.
这是否意味着:如果我为父级指定 font-size: 2em
并为子级指定 font-size:继承
,结果与指定 font-size: 2em
到子级(因为 2em
是其父级的指定值)?
来 self 的样本JSFiddle ,事实并非如此:
#parent {
font-size: 2em;
}
#child-0 {
font-size: inherit;
}
#child-1 {
font-size: 2em;
}
<div id="parent">I am parent.
<div id="child-0">I am child 0.</div>
<div id="child-1">I am child 1.</div>
</div>
谁能解释一下吗?
最佳答案
让我们看看the inherit
value :
Each property may also have a cascaded value of 'inherit', which means that, for a given element, the property takes the same specified value as the property for the element's parent.
现在的问题是,如何处理指定值?
答案在Computed Values下:
6.1.2 Computed values
Specified values are resolved to computed values during the cascade [...]
计算值是如何处理的?
[...] 'em' and 'ex' units are computed to pixel or absolute lengths.
(已添加强调)
这意味着当子级继承父级字体大小时,它将继承其父级计算值(以像素为单位 (px
)),默认情况下 2em
为 32px。
当子项被赋予自己的 em
值时,它将根据其父项字体大小的计算值计算其值(以 px 为单位)。 2em
将使子字体大小加倍。
在您的示例中:
- 父级上的 2em = 32px
- 继承子级 = 32px(父级的计算值)
- 子项上的 2em = 64px(子项的计算值,是父项值的两倍)
这反射(reflect)在您的示例中:
#parent {
font-size: 2em;
}
#child-0 {
font-size: inherit;
}
#child-1 {
font-size: 2em;
}
<div id="parent">I am parent.
<div id="child-0">I am child 0 and I inherit my parents computed font-size of 32px</div>
<div id="child-1">I am child 1 and I double my font-size with 2em. This means that I have a font-size of 64px</div>
</div>
关于css - 计算 font-size 的继承值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30769800/