前言
- 大家好,我是_Peach,今天记录下H5中的rem小技巧
什么是rem布局
- 我们已知px是固定值像素单位,em是相对于当前父级的字体大小定义的。而rem是根元素的字体大小定义的,相对于前两位,rem是比较好用和使用最多的单位
- 本次测试使用了postcss(版本8.4.12),postcss-pxtorem(版本5.1.1)amfe-flexible(版本2.2.1)
代码实现
- 使用npm安装以下依赖包
"amfe-flexible": "^2.2.1",
"postcss": "^8.4.12",
"postcss-pxtorem": "^5.1.1",
- 在根目录下新建postcss.config.js文件,配置以下代码
module.exports = {
plugins: {
'postcss-pxtorem': {
rootValue: 37.5, // 75表示750设计稿,37.5表示375设计稿
propList: ['*']
}
}
}
- 在组件中使用
<template>
<div>
<div class="box">盒子</div>
</div>
</template>
<script>
export default {
}
</script>
<style>
.box{
width: 100px;
height: 100px;
font-size: 50px;
background: #ccc;
}
</style>
- 可以看到html的font-size会动态变更
5.编写css代码的时候根据设计稿(可在postcss.config.js里面配置)的px单位来写,插件会自动生成rem单位