看到標(biāo)題不禁想到了rem...rem有種奇怪的魔力
個(gè)人總結(jié)適配大體分為兩類:
- 縮放類
- 媒體查詢類
對(duì)比 | 縮放類 | 媒體查詢類 |
---|---|---|
實(shí)現(xiàn)方案 | rem冻记、scale | @media |
優(yōu)點(diǎn) | 一套代碼可以適用不同大小的設(shè)備苟弛,節(jié)約人力 | 在滿足看清的情況下,可以展示更多的內(nèi)容 |
缺點(diǎn) | 在更大的設(shè)備下,看到更大的內(nèi)容,而非更多的內(nèi)容 | 需要針對(duì)不同尺寸段設(shè)置單獨(dú)的css,需要更多的人力投入 |
當(dāng)前大部分應(yīng)該使用的rem適配矢沿,所以...跟著大家總是沒錯(cuò)滴...自己嘗試用postcss-pxtorem來(lái)做適配
食用方法
通用文件rem.js
function setRem() {
// 設(shè)計(jì)稿320px 默認(rèn)大小16px; 320px = 20rem
// 設(shè)計(jì)稿375px 默認(rèn)大小37.5px; 375px = 10rem
let htmlWidth = document.documentElement.clientWidth || document.body.clientWidth;
//得到html的Dom元素
let htmlDom = document.getElementsByTagName('html')[0];
//設(shè)置根元素字體大小
htmlDom.style.fontSize = htmlWidth / 20 + 'px';
}
// 初始化
setRem();
// 改變窗口大小時(shí)重新設(shè)置 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: ["*"],
})
]
}
}
}
};
備注:如果報(bào)錯(cuò):Error: PostCSS plugin postcss-pxtorem requires PostCSS 8捣鲸,切換postcss-pxtorem@5.1.1