下载插件:npm install postcss-pxtorem --save-dev
下载完后进行配置如下:
// 在项目根目录下创建postcss.config.js文件
module.exports = {
plugins: {
'autoprefixer': {
browsers: ['Android >= 4.0', 'iOS >= 7']
},
'postcss-pxtorem': {
rootValue: 16,//结果为:设计稿元素尺寸/16,比如元素宽320px,最终页面会换算成 20rem
propList: ['*']
}
}
}
还需要根据屏幕的大小计算合理的html 元素font-size 值的rem.js文件建议放在static目录下代码如下:
// 设置 rem 函数
function setRem () {
// 320 默认大小16px; 320px = 20rem ;每个元素px基础上/16
let htmlWidth = document.documentElement.clientWidth || document.body.clientWidth;
//得到html的Dom元素
let htmlDom = document.getElementsByTagName('html')[0];
//设置根元素字体大小
htmlDom.style.fontSize= htmlWidth/20 + 'px';
console.log( htmlDom.style.fontSize,'设置根元素字体大小--------------')
}
// 初始化
setRem();
// 改变窗口大小时重新设置 rem
window.onresize = function () {
setRem()
}
然后在main.js文件中引入
import '../static/rem'
移动端适配通过插件postcss-pxtorem实现
最新推荐文章于 2024-06-05 14:15:00 发布