在开发中经常会遇到响应式适配的问题,常用的就是通过 rem 单位来适配。这里介绍通过使用 postCssPxToRem + flexible.js 进行rem响应式适配。
移动端也可使用此方案,或使用 https://cdn.jamesy.cn/gh/JamesY-Jey/public/assets/js/rem.js 的代码。

参考文章:
vue3+vite+ts项目搭建-postcss-pxtorem
vue3.0+vite 使用 postcss-pxtorem 实现移动自适应(px转rem)

这里的环境是 Vite + Vue3

1. 安装 postCssPxToRem

1
npm i postcss-pxtorem -D

2. 配置

  • 新建 postcss.config.js 文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
module.exports = {
plugins: {
autoprefixer: {
overrideBrowserslist: [
'Android 4.1',
'iOS 7.1',
'Chrome > 31',
'not ie <= 11', //不考虑IE浏览器
'ff >= 30', //仅新版本用“ff>=30
'> 1%', // 全球统计有超过1%的使用率使用“>1%”;
'last 2 versions' // 所有主流浏览器最近2个版本
],
grid: true // 开启grid布局的兼容(浏览器IE除外其他都能兼容grid,可以关闭开启)
},
'postcss-pxtorem': {
rootValue: 192, // 设计稿宽度除以 10, 开头大写的Px 不转换 => height: 100Px, 内联样式不转换,需要 / 75 转成 rem
unitPrecision: 6, // 计算结果保留 6 位小数
selectorBlackList: ['.no-rem', 'no-rem'], // 要忽略的选择器并保留为px。
propList: ['*'], // 可以从px更改为rem的属性 感叹号开头的不转换
replace: true, // 转换成 rem 以后,不保留原来的 px 单位属性
mediaQuery: true, // 允许在媒体查询中转换px。
minPixelValue: 2, // 设置要替换的最小像素值。
exclude: /node_modules/i // 排除 node_modules 文件(node_modules 内文件禁止转换)
}
}
}
  • Vite环境中不生效可在 vite.config.js 中添加配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import postCssPxToRem from 'postcss-pxtorem'

// 配置项中添加
css: {
postcss: {
plugins: [
postCssPxToRem({
rootValue: 192, // 设计稿宽度除以 10, 开头大写的Px 不转换 => height: 100Px, 内联样式不转换,需要 / 75 转成 rem
unitPrecision: 6, // 计算结果保留 6 位小数
selectorBlackList: ['.no-rem', 'no-rem'], // 要忽略的选择器并保留为px。
propList: ['*'], // 可以从px更改为rem的属性 感叹号开头的不转换
replace: true, // 转换成 rem 以后,不保留原来的 px 单位属性
mediaQuery: false, // 允许在媒体查询中转换px。
minPixelValue: 2, // 设置要替换的最小像素值。
exclude: /node_modules/i // 排除 node_modules 文件(node_modules 内文件禁止转换)
}),
]
},
}

3. 引入 flexible.js

1
npm i lib-flexible -D
  • main.js 中引入
1
import 'lib-flexible/flexible'