em 单位

时间:2023-03-09 13:38:55
em 单位

Lea verou 的话:

当某些值相互依赖时,应该把它们的相互关系用代码表达出来。

通常情况下,我们会希望字号和其他尺寸能够跟父元素的字号建立关联,此时em就很好的表达了这种关系。

CSS Values and Units Module Level 3中,有一个相对长度单位em:

em unit

Equal to the computed value of the font-size property of the element on which it is used.

翻译:

em 等价于元素font-size的计算值

那么问题来了,如果元素的font-size用的是em单位呢?MDN指出:

For most font-relative units (such as em and ex), the font size is relative to the parent element's font size.

翻译:

font-size 属性的emex单位值相对于父元素的字号

这其实意味着,font-sizeem和%单位的作用是一样的。

到这里为止em的用法已经清楚了:

  1. 默认继承父元素的font-size,如果通过em显示指定元素的font-size,作用等于%,相对于父元素的font-size计算。
  2. 元素的其他属性使用em单位,em等价于元素font-size的计算值

注意两点,

  1. font-size默认会继承,但是诸如替换元素(诸如buttoninput),不会继承,规范上大意是说,替换元素的样式超出了 CSS 的范畴。
  2. line-heightem时,直观来看,等价于用数字,但是继承的时候会出现问题,所以line-height通常推荐用数字而不是用em

比如:

.green {
line-height: 1.1;
border: solid limegreen;
} .red {
line-height: 1.1em;
border: solid red;
} h1 {
font-size: 30px;
} .box {
width: 18em;
display: inline-block;
vertical-align: top;
font-size: 15px;
}
<div class="box green">
<h1>Avoid unexpected results by using unitless line-height.</h1>
length and percentage line-heights have poor inheritance behavior ...
</div> <div class="box red">
<h1>Avoid unexpected results by using unitless line-height.</h1>
length and percentage line-heights have poor inheritance behavior ...
</div> <!-- The first <h1> line-height is calculated from its own font-size (30px × 1.1) = 33px -->
<!-- The second <h1> line-height results from the red div's font-size (15px × 1.1) = 16.5px, probably not what you want -->

结果如图:

em 单位