rem

date
Mar 9, 2023
slug
deepcss-relative-rem
status
Published
tags
深入解析CSS
summary
CSS Relative unit
type
Post
<html>是顶级根节点,根节点是所有其他元素的祖先节点。根节点有一个伪类选择器(:root),可以用来选中自己。:root等价于类型选择器html,但是:root的优先级相当于一个类名,而不是一个标签。
rem 是 root em 的缩写。rem 不是相对于当前元素,而是相对于根元素的单位。不管在文档的什么位置使用rem,1.2rem都有相同的计算值:1.2乘以根元素的字体。
通常使用rem 设置字号,用px设置边框,用em设置其他大部分属性,尤其是内边框、外边距和圆角(有时用百分比设置容器的宽度)。这样字号是可预测的,同时还能在其他因素改变元素字号时,借助em缩放内外边距。用px定义边框用于绘制精致的线条。
<div class="panel">
 <h2>Single-origin</h2>
 <div class="panel-body">
 We have built partnerships with small farms around the world to
 hand-select beans at the peak of season. We then carefully roast
 in <a href="/batch-size">small batches</a> to maximize their
 potential.
 </div>
</div>
.panel{
    padding: 1em;
    border-radius: 0.5em;  //用em设置内边距和圆角
    border: 1px solid #999;  //用 1px 设置一条细边
}
.panel > h2{
    margin-top: 0; //将面板顶部的多余空间移除
    font-size: 0.8rem; //用 rem 设置标题的字号
}

© shallrise 2025