看到標題不禁想到了rem...rem有種奇怪的魔力
個人總結適配大體分為兩類:
- 縮放類
- 媒體查詢類
| 對比 | 縮放類 | 媒體查詢類 |
|---|---|---|
| 實現(xiàn)方案 | rem、scale | @media |
| 優(yōu)點 | 一套代碼可以適用不同大小的設備,節(jié)約人力 | 在滿足看清的情況下,可以展示更多的內(nèi)容 |
| 缺點 | 在更大的設備下,看到更大的內(nèi)容,而非更多的內(nèi)容 | 需要針對不同尺寸段設置單獨的css,需要更多的人力投入 |
當前大部分應該使用的rem適配,所以...跟著大家總是沒錯滴...自己嘗試用postcss-pxtorem來做適配
食用方法
通用文件rem.js
function setRem() {
// 設計稿320px 默認大小16px; 320px = 20rem
// 設計稿375px 默認大小37.5px; 375px = 10rem
let htmlWidth = document.documentElement.clientWidth || document.body.clientWidth;
//得到html的Dom元素
let htmlDom = document.getElementsByTagName('html')[0];
//設置根元素字體大小
htmlDom.style.fontSize = htmlWidth / 20 + 'px';
}
// 初始化
setRem();
// 改變窗口大小時重新設置 rem
window.onresize = function () {
setRem()
}
方法一
package.json配置
// npm install postcss-pxtorem
"postcss": {
"plugins": {
"autoprefixer": {},
"postcss-pxtorem": {
"rootValue": 16,
"propList": ["*"]
}
}
},
// main.js
import './rem.js'
方法二
postcss.config.js配置(文件沒有自己創(chuàng)建)
// npm install postcss-pxtorem
module.exports = {
plugins: {
'autoprefixer': {
browsers: ['Android >= 4.0', 'iOS >= 7']
},
'postcss-pxtorem': {
rootValue: 16,
propList: ['*']
}
}
}
// main.js
import './rem.js'
方法三
vue.config.js配置
// npm i amfe-flexible -S npm i postcss-pxtorem -D
module.exports = {
css: {
loaderOptions: {
postcss: {
plugins: [
require("autoprefixer")({
// 配置使用 autoprefixer
overrideBrowserslist: ["last 15 versions"]
}),
require("postcss-pxtorem")({
rootValue: 16, // 換算的基數(shù)
unitPrecision: 6, // 允許rem單位精度
propWhiteList: [], // 允許換算白名單(空數(shù)組表示禁用白名單,全部轉(zhuǎn)換)
propBlackList: [], // 不允許轉(zhuǎn)換名單
exclude: /node_modules/, // 排除文件夾
selectorBlackList: ["ig"], // 忽略的選擇器,保留px
// propList: ["*"],
})
]
}
}
}
};
備注:如果報錯:Error: PostCSS plugin postcss-pxtorem requires PostCSS 8,切換postcss-pxtorem@5.1.1