postcss-pxtorem配合lib-flexible,非常方便,vue-cli3.0后,項目配置被大大精簡了。
安裝 flexible和 postcss-px2rem(命令行安裝)
npm install lib-flexible --save
npm install postcss-pxtorem --save-dev
或者:
npm install postcss-px2rem --save-dev
postcss-pxtorem會將px轉(zhuǎn)換為rem,rem單位用于適配不同寬度的屏幕,根據(jù)<html>標(biāo)簽的font-size值來計算出結(jié)果,1rem=html標(biāo)簽的font-size值。
引入lib-flexible
在項目入口文件main.js 中引入lib-flexible
import 'lib-flexible'
配置postcss-pxtorem
1.vue.config.js中配置
放在vue-cli3 項目中vue.config.js中(vue-cli3默認(rèn)情況下沒有vue.config.js,需要手動在項目根目錄創(chuàng)建)
//////////////////待補充
2.postcss-pxtorem 在postcss.config.js中配置
module.exports = {
plugins: {
'autoprefixer': {
browsers: ['Android >= 4.0', 'iOS >= 7']
},
'postcss-pxtorem': {
rootValue: 75,//
propList: ['*']// 設(shè)置哪些屬性可以從px變?yōu)閞em。“!”表示不匹配,“ !font* ”表示不匹配字體相關(guān)屬性
}
}
}
或者postcss-px2rem
module.exports = {
css: {
loaderOptions: {
css: {},
postcss: {
plugins: [
require('postcss-px2rem')({
remUnit: 75
})
]
}
}
}
}
配置完成后,重啟一下項目。
使用
下面來看我們的代碼,代碼中我們直接用px來寫寬高:

image.png

image.png
再來看下html根字體的大小

image.png

image.png
rootValue:通常我們是根據(jù)設(shè)計圖來定這個值,原因很簡單,便于開發(fā)。假如設(shè)計圖給的寬度是750,我們通常就會把rootValue設(shè)置為75,這樣我們寫樣式時,可以直接按照設(shè)計圖標(biāo)注的寬高來1:1還原開發(fā)。
即:如果你設(shè)計稿的長度是750基數(shù)的可以將rootValue的值修改為75