- rem 相对于根元素进行计算,若根元素的 font-size为16px,则其他元素的2rem的大小为 2*16 = 32px 。(根元素是指没有父节点的 dom 节点,在html中是html标签)
- em相对于最近的父元素进行计算,若父元素的 font-size为16px,则子元素2em的大小为 2*16 = 32px
演示范例如下:
直观效果为:rem 只和根元素有关,不会因嵌套而层层放大。而 em 因和父元素有关,嵌套越深,放大倍数越多。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>rem和em效果演示</title>
</head>
<body>
<div class="mainBox">
<p>根元素的font-size为20px</p>
<div class="box1">
<p>box1的font-size为2rem的效果为40px</p>
<div>
<p class="child">box1的子元素2rem的效果仍为40px</p>
</div>
</div>
<div class="box2">
<p>box2的font-size为2em效果为40px</p>
<div>
<p class="child">box2的子元素2em的效果为80px</p>
</div>
</div>
<div class="box3">
<p>box3的font-size为12px</p>
<div>
<p class="child">box3的子元素2em的效果为24px</p>
</div>
</div>
</div>
<style>
.mainBox {
display: flex;
}
div {
border: 1px solid;
}
html {
font-size: 20px;
}
.box1 {
font-size: 2rem;
}
.box1 .child {
font-size: 2rem;
}
.box2 {
font-size: 2em;
}
.box2 .child {
font-size: 2em;
}
.box3 {
font-size: 12px;
}
.box3 .child {
font-size: 2em;
}
</style>
</body>
</html>
最佳实践
若某些模块,如范例中的 box3 需要单独设置与根元素不同的字体大小,则在box3内部的子元素需随 box3 字体大小变化的内容,不能使用 rem 为单位,而应使用 em。
em 维护的是某模块内嵌套元素固定的比例关系
其他情况,都推荐使用 rem ,以便通过根元素字体大小的适配,就能实现整个网页的自适应。