em 单位

Lea verou 的话:css

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

一般状况下,咱们会但愿字号和其余尺寸可以跟父元素的字号创建关联,此时em就很好的表达了这种关系。less

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.code

翻译:htm

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

那么问题来了,若是元素的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.element

翻译:get

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 -->

结果如图:

相关文章
相关标签/搜索