三、rem
指相对于根元素的字体大小的单位。
根字体大小通常设置为10px,方便换算。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
html {
/* 设置根字体大小 */
font-size: 10px;
}
div{
font-size: 0.5rem;
}
</style>
</head>
<body>
<div>
文字内容
</div>
</body>
</html>
案例
监听屏幕变化,字体等比例变化
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
var c = () => {
// 获取设备的宽度
let width = document.documentElement.clientWidth;
let width2 = (20 * (width / 320) > 40 ? 40 + "px" : (20 * (width / 320) + "px"));
document.documentElement.style.fontSize = width2;
console.log("width2", width2);
}
window.addEventListener('load', c);
window.addEventListener('resize', c);
</script>
<style>
html {
font-size: 10px;
}
div {
font-size: 1rem;
}
</style>
</head>
<body>
<div>文字内容</div>
</body>
</html>