前端使用 rem 作为单位进行响应式布局时,常见的做法是动态调整根元素(html)的字体大小,以便让页面能够自适应不同分辨率的屏幕。这通常通过 JavaScript 脚本计算和设置 html 的 font-size
1. 通过设计稿宽度计算基准
假设设计稿宽度是 750px,通常希望 1rem 对应 100px,这样就可以根据屏幕宽度动态调整 font-size:
javascript
复制代码
function setRemBase() {
const baseSize = 100; // 1rem = 100px
const designWidth = 750; // 设计稿宽度
const clientWidth = document.documentElement.clientWidth || window.innerWidth;
const fontSize = (clientWidth / designWidth) * baseSize;
document.documentElement.style.fontSize = `${fontSize}px`;
}
// 初始化
setRemBase();
// 窗口大小改变时重新计算
window.addEventListener('resize', setRemBase);
这样一来,设计稿上的 100px 宽度对应页面中的 1rem,实现了页面元素的等比例缩放。
推算过程:
2. 使用 PostCSS 自动转换 px 到 rem
配置 PostCSS 插件,例如 postcss-pxtorem,可以在编译阶段将 px 自动转换为 rem 值。
在 .postcssrc.js 中:
javascript
复制代码
module.exports = {
plugins: {
'postcss-pxtorem': {
rootValue: 100, // 1rem 对应100px
propList: ['*'], // 转换所有属性
},
},
};