前言:
在开发中我们会遇到ui给我们一套750px 的设计稿, 但是我们使用vant组件库开发的话,里面的都是写好了的,它里面的是375px
我们要做的是怎么把给的需求完成:
1.使用使用rem适配
-
1安装 amfe-flexible插件
-
yarn add amfe-flexible
-
npm i amfe-flexible
-
-
在main.js导入
-
import "amfe-flexible"
-
-
安装postcss-pxtorem
-
yarn add postcss-pxtorem@5.0.0
-
-
配制详情
创建postcss.config.js(加载css时使用)
module.exports={
plugins:{
rootValue:基准值(37.5),
propList:哪些css需要转换,针对的css选择["*"]
}
}html 下font-size=屏幕宽度/10
设计稿:1080 723px用rem表示 723/108rem
const path = require('path')
module.exports = ({ file }) => {
// 如果是vant的css需要转换,它的文件都是来自于node_modules/vant
// file.dirname:需要转换的文件路径
const base = file.dirname.includes(path.join('node_modules', 'vant'))
? 37.5
: 75
return {
plugins: {
'postcss-pxtorem': {
rootValue: base,
propList: ['*']
}
}
}
}
// module.exports={
// plugins:{
// // 二套:ui一套 750px vant一套 375px
// rootValue:基准值(37.5), // 设计稿/10后的值
// propList:哪些css需要转换,针对的css选择["*"] // 哪些css需要转换
// }
// }
// 2:下载与配制 postcss-pxtorem插件
const path = require("path");
module.exports = ({ file }) => {
// 如果是vant的css需要转换,它的文件都是来自于node_modules/vant
// file.dirname:需要转换的文件路径
// 判断当前读取的文件路径是否包含vant,如果包含就是在解析vant的css,依赖设计稿是375宽度标准转换
// 如果不包含说明是自己写的css,就依赖ui的设计稿宽度标准进行计算
const base = file.dirname.includes(path.join("node_modules", "vant"))
? 37.5
: 75;
return {
plugins: {
"postcss-pxtorem": {
rootValue: base,
propList: ["*"],
},
},
};
};
2. vw适配
使用步骤如下
vw:100vw=== 屏幕的百分百 vh
相对屏幕的百分比单位
百分比是相对父级
实现过程:
安装插件
yarn add postcss-px-to-viewport -D
配制
根目录下的postcss.config.js
const path = require("path"); module.exports = ({ file }) => { const base = file.dirname.includes(path.join("node_modules", "vant")) ? 375 : 750; return { plugins: { "postcss-px-to-viewport": { viewportWidth: base, }, }, }; };