-
安装 postcss-pxtorem:
npm install postcss-pxtorem -D
// 用来把px转rem
npm install amfe-flexible -D
// 用来修改根元素字体大小 -
配置 vite.config.ts:
import { defineConfig } from 'vite'
import postcssPxtoRem from 'postcss-pxtorem'
export default defineConfig({
css: {
postcss: {
plugins: [
postcssPxtoRem({
rootValue: 192, // 按照自己的设计稿修改 1920/10
unitPrecision: 5, // 保留到5位小数
selectorBlackList: ['ignore', 'tab-bar', 'tab-bar-item'], // 忽略转换正则匹配项
propList: ['*'],
replace: true,
mediaQuery: false,
minPixelValue: 0
})
]
}
}
})
- 再
main.ts
文件中引入amfe-flexible
import 'amfe-flexible'
- 在样式中使用 px 作为单位:
.content {
font-size: 20px;
}
- 如果是
行内样式
或者js赋值
的px这个插件不会转行rem,这个时候需要在赋值的时候/192
<div :style="{width: 1000 / 192 + 'rem', height: 500 / 192 + 'rem'}"></div>
- 使用此插件后
不推荐使用grid布局
,会出现一些奇奇怪怪的尺寸兼容问题