Vant 中的样式默认使用 px
作为单位,如果需要使用 rem
单位,推荐使用以下两个工具:
额外增加一点:
flexible.js插件是一个终端设备适配的解决方案。flexible.js插件通过实现rem单位的自适应,来达到实现不同终端之间页面适配的目的。
1.下载 postcss-pxtorem 和 lib-flexible 包
> yarn add amfe-flexible
> yarn add postcss-pxtorem
2.main.js 中 import ‘amfe-flexible’ 加载执行该模块
import 'amfe-flexible'
3.在项目根目录中创建 .postcssrc.js
文件
/**
* PostCSS 配置文件
*/
module.exports = {
// 配置要使用的 PostCSS 插件
plugins: {
// 配置使用 autoprefixer 插件
// 作用:生成浏览器 CSS 样式规则前缀
// VueCLI 内部已经配置了 autoprefixer 插件
// 所以又配置了一次,所以产生冲突了
// 'autoprefixer': { // autoprefixer 插件的配置
// // 配置要兼容到的环境信息
// browsers: ['Android >= 4.0', 'iOS >= 8']
// },
// 配置使用 postcss-pxtorem 插件
// 作用:把 px 转为 rem
'postcss-pxtorem': {
rootValue ({ file }) {
return file.indexOf('vant') !== -1 ? 37.5 : 75
},
propList: ['*']
}
}
}
4、配置完毕,重新启动服务
最后测试:刷新浏览器页面,审查元素的样式查看是否已将 px
转换为 rem
。
注意: 该插件不能转换行内样式中的 px
,例如 <div style="width: 200px;"></div>
运行项目后会报错 PostCSS plugin postcss-pxtorem requires PostCSS 8.
需要降低 postcss-pxtorem 的版本
yarn remove postcss-pxtorem -D
yarn add postcss-pxtorem@5.1.1 -D