js实现rem
rem 的实现原理
rem(root em)是相对于根元素(html)字体大小的单位。通过动态调整根元素的字体大小,可以实现页面元素的等比缩放,适配不同屏幕尺寸。
设置根元素字体大小
在HTML文件的<head>部分添加以下代码,确保脚本在页面加载时立即执行:
<script>
document.documentElement.style.fontSize = document.documentElement.clientWidth / 10 + 'px';
</script>
这段代码将根元素字体大小设置为视口宽度的1/10。例如,375px宽度的设备会得到37.5px的根字体大小。
使用 rem 单位
在CSS中,所有需要适配的元素尺寸使用rem单位。例如:
.box {
width: 2rem; /* 相当于2倍的根字体大小 */
height: 3rem;
font-size: 0.8rem;
}
动态调整脚本
为了应对窗口大小变化,需要添加resize事件监听:
function setRemUnit() {
const docEl = document.documentElement;
const rem = docEl.clientWidth / 10;
docEl.style.fontSize = rem + 'px';
}
window.addEventListener('resize', setRemUnit);
window.addEventListener('pageshow', function(e) {
if (e.persisted) setRemUnit();
});
媒体查询兼容方案
为极端情况添加媒体查询作为后备方案:
@media screen and (max-width: 320px) {
html { font-size: 32px; }
}
@media screen and (min-width: 540px) {
html { font-size: 54px; }
}
PostCSS 自动转换
在构建工具中配置PostCSS插件,自动将px转换为rem:
// postcss.config.js
module.exports = {
plugins: {
'postcss-pxtorem': {
rootValue: 37.5, // 设计稿宽度/10
propList: ['*'],
selectorBlackList: [/^html$/]
}
}
}
设计稿适配技巧
假设设计稿宽度为375px:

- 开发时直接使用设计稿标注的px值
- 通过构建工具自动转换为rem
- 1px边框问题可使用transform scale解决






