- 装包
cnpm install postcss-pxtorem -D
- 修改根目录 .postcssrc.js 文件
// https://github.com/michael-ciniawsky/postcss-load-config
module.exports = {
"plugins": {
"postcss-import": {},
"postcss-url": {},
// to edit target browsers: use "browserslist" field in package.json,
"autoprefixer": {},
"postcss-pxtorem": {
"rootValue": 32,
"propList": ["*"]
}
}
}
- 引入rem.js
// 基准大小
const baseSize = 32
// 设置 rem 函数
function setRem () {
// 当前页面宽度相对于 750 宽的缩放比例,可根据自己需要修改。
var scale = document.documentElement.clientWidth / 412
// 设置页面根节点字体大小
document.documentElement.style.fontSize = (baseSize * Math.min(scale, 2)) + 'px'
}
// 初始化
setRem()
// 改变窗口大小时重新设置 rem
window.onresize = function () {
setRem()
}