rem

rem

定义相同文字的大小,但在不同的设备上应该展示不同的像素数。rem相对于html标签fontSize大小的单位。

rem设置

根据屏幕的宽度定义根元素fontSize大小

定义函数把像素转rem

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 定义最大 fontSize
const MAX_FONT_SIZE = 42;

// 监听HTML文档被解析完成的事件
document.addEventListener('DOMContentLoaded', () => {
// 获取html标签
const html = document.querySelector('html');
// 屏幕的宽度除以10,获取根元素 fontSize 标准
let fontSize = window.innerWidth / 10;
// 获取到 fontSize 标签不允许超过我们定义的最大值
fontSize = fontSize > MAX_FONT_SIZE ? MAX_FONT_SIZE : fontSize
// 定义根元素 fontSize 大小
html.style.fontSize = fontSize + 'px';
})

运算规则

1
2
3
4
5
6
7
// I6、6s、7为设计基础
// 定义预计根元素 fontSize
$rootFontSize: 375 / 10;
// 定义像素转化为 rem 函数
@function px2rem ($px) {
@return $px / $rootFontSize + rem;
}