借 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
andex
), the font size is relative to the parent element's font size.element
翻译:get
font-size
属性的em
和ex
单位值相对于父元素的字号
这其实意味着,font-size
的em
和%单位的做用是同样的。
到这里为止em
的用法已经清楚了:
font-size
,若是经过em
显示指定元素的font-size
,做用等于%,相对于父元素的font-size
计算。em
单位,em
等价于元素font-size
的计算值注意两点,
font-size
默认会继承,可是诸如替换元素(诸如button
、input
),不会继承,规范上大意是说,替换元素的样式超出了 CSS 的范畴。line-height
用em
时,直观来看,等价于用数字,可是继承的时候会出现问题,因此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 -->
结果如图: