概念 : postcss-pxtorem是PostCSS的插件,用于将像素单元生成rem单位。
一、下载依赖 postcss-pxtorem 推荐版本"5.1.1
npm install postcss-pxtorem -D
yarn add postcss-pxtorem
二、新建一个rem.js的文件,在main.js中引用
const baseSize = 192;
function setRem() {
const scale = window.screen.width / 1920;
document.documentElement.style.fontSize =
baseSize * Math.min(scale, 2) + "px";
}
setRem();
window.onresize = function () {
setRem();
};
三、在vue.confing 写入postcss-pxtorem 配置
module.exports = {
css: {
loaderOptions: {
postcss: {
plugins: [
// 兼容浏览器,添加前缀
require("autoprefixer")({
overrideBrowserslist: [
"Android 4.1",
"iOS 7.1",
"Chrome > 31",
"ff > 31",
"ie >= 8",
//'last 10 versions', // 所有主流浏览器最近10版本用
],
grid: true,
}),
require("postcss-pxtorem")({
rootValue: 192, //设计稿宽度%10 比如 1920
exclude: /(node_module)/, //默认false,可以(reg)利用正则表达式排除某些文件夹的方法,例如/(node_module|src)/
propList: ["*"], //是一个存储哪些将被转换的属性列表,这里设置为["*"]全部,假设需要仅对边框进行设置,可以写]['*','!border*']
//selectorBlackList :['.box'],//,那例如fs-xl类名,里面有关px的样式将不被转换,这里也支持正则写法。
replace: true, //替换包含rems的规则。
mediaQuery: false, //(布尔值)允许在媒体查询中转换px。
minPixelValue: 0, //设置要替换的最小像素值(3px会被转rem)。 默认 0
}),
],
},
},
},
}
四、补充 忽略单个属性的最简单方法是在像素单位声明中使用大写字母,将px写为Px。
.ignore {
border: 2Px solid; // ignored
border-width: 2PX; // ignored
}
五、开始启动项目 yarn serve 看结果吧
若有疑问欢迎小伙伴们留言...
小编的Github 地址 https: