前端vue 项目px转为rem的自适应解决方案
postcss-pxtorem(或是postcss-px2rem)
npm install postcss-pxtorem amfe-flexible --save-dev
在入口文件 main.js
中引入 amfe-flexible
(响应式适配):
main.js
import 'amfe-flexible' // 自动设置 html 的 font-size
vue.config.js
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
css: {
loaderOptions: {
postcss: {
postcssOptions: {
plugins: [
require('postcss-pxtorem')({
rootValue: 192,
unitPrecision: 5,
propList: ['*']
})
]
}
}
}
}
})
rootValue 的值是根据屏幕分辨率宽或是设计稿宽度除以 10,例如1920 * 1080的设计稿,此处rootValue:192
但是每次打开调试工具栏后,或是改变浏览器窗口大小, html 的 font-size 总是会自动变化,很不方便。
可以将 html 和 body 的 font-size 设置成固定值然后不使用 amfe-flexible
<style>
html {
font-size: 192px;
}
body {
font-size: 16px;
}
</style>
此种方案的样式需要写在css中,对于行内style中的样式不起作用
为使行内样式也起作用可以使用 style-rem-loader
npm install style-rem-loader --save-dev
chainWebpack: (config) => {
config.module
.rule('vue')
.test(/\.vue$/)
.use('style-rem-loader')
.loader('style-rem-loader')
.options({
viewportWidth: 1920,
unitPrecision: 5
})
},