如果需要使用 rem 单位进行适配,推荐使用以下两个工具:
PostCSS 示例配置
下面提供了一份基本的 PostCSS 示例配置,可以在此配置的基础上根据项目需求进行修改。
- // postcss.config.js
- module.exports = {
- plugins: {
- 'postcss-pxtorem': {
- rootValue: 37.5,
- propList: ['*'],
- },
- },
- };
一、概念
postcss-pxtorem是PostCSS的插件,用于将像素单元生成rem单位。
二、使用
安装依赖之后,将postcss-pxtorem的配置都放到了vue.config.js中。

module.exports = {
productionSourceMap: false, // 生产环境是否生成 SourceMap
css: {
loaderOptions: {
postcss: {
plugins: [
require(‘postcss-pxtorem‘)({
rootValue: 16,
unitPrecision: 5,
propList: ['font', 'font-size', 'line-height', 'letter-spacing'],
selectorBlackList: [],
replace: true,
mediaQuery: false,
minPixelValue: 0,
exclude: /node_modules/i
}),
]
}
}
},
}
三、参数解释
1)rootValue(Number | Function)表示根元素字体大小或根据input参数返回根元素字体大小。
2)unitPrecision (Number)允许REM单位增加的十进制数字。
3)propList (Array)可以从px更改为rem的属性。
*启用所有属性。例:['*']*在单词的开头或结尾使用。(['*position*']将匹配background-position-y)!不匹配的属性。例:['*', '!letter-spacing']['*', '!font*']4)selectorBlackList (Array)要忽略的选择器,保留为px。
['body'] 将匹配 .body-class[/^body$/]将匹配body但不匹配.body5)replace (Boolean)替换包含rems的规则。
6)mediaQuery (Boolean)允许在媒体查询中转换px。
7)minPixelValue(Number)设置要替换的最小像素值。
8)exclude(String, Regexp, Function)要忽略并保留为px的文件路径。
'exclude' 将匹配 \project\postcss-pxtorem\exclude\path/exclude/i 将匹配 \project\postcss-pxtorem\exclude\pathfunction (file) { return file.indexOf('exclude') !== -1; }四、补充
忽略单个属性的最简单方法是在像素单位声明中使用大写字母,将px写为Px。
比如:
.ignore {
border: 1Px solid; // ignored
border-width: 2PX; // ignored
}