欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 新车 > 前端vue 项目px转为rem的自适应解决方案

前端vue 项目px转为rem的自适应解决方案

2025/4/19 13:07:43 来源:https://blog.csdn.net/weixin_38883338/article/details/147188701  浏览:    关键词:前端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})},

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词