移动端自适应方案:从px到rem的换算逻辑

因为UI稿中的组件单位默认为px,当在vue移动端项目中一比一还原后,会出现设备分辨率越大元素越小的问题,所以要通过元素缩放的形式进行移动端适配。

解决方案为(vue2.x):amfe-flexible + postcss-pxtorem

amfe-flexible:配置可伸缩方案,主要是将 1rem 设为 viewWidth/10
postcss-pxtorem:是 postcss 的插件,用于将像素 px 单元生成 rem 单位;

  1. 安装依赖:
    "npm install amfe-flexible postcss-pxtorem -D"

  2. 配置 amfe-flexible
    "main.js" 文件中引入amfe-flexibleimport 'amfe-flexible'

  3. 配置 postcss 插件,在根目录增加 postcss.config.js 中增加配置:


module.exports = {
  plugins: {
    "postcss-pxtorem": {
      rootValue: 37.5,
      propList: ["*"],
      unitPrecision: 5
    },
  },
};

也可以在 vue.config.js 中增加如下配置:


const { defineConfig } = require('@vue/cli-service');
const pxtorem = require('postcss-pxtorem');

module.exports = defineConfig({
  transpileDependencies: true,
  css: {
    loaderOptions: {
      postcss: {
        postcssOptions: {
          plugins: [
            pxtorem({
              rootValue:37.5,
              propList: ['*']
            })
          ]
        }
      }
    }
  }
})

重新启动项目后,调整设备的宽度,发现html标签自动生成的style中 font-size 的值跟随设备变化,说明 amefe-flexible 配置成功;
css中设置某个元素的宽度为 375px,运行后浏览器中查看编译为 10rem,即 375/rootValue(37.5),说明配置成功

  1. pxtorem各项配置作用说明:

rootValue(Number|Function) 表示根元素字体大小或根据参数返回根元素字体大小,计算结果一般设置为 设计稿宽度 / rootValue = 10rem

已知组件库项目设计稿宽度为 375px,所以 rootValue 应为 37.5,但vue项目设计稿宽度为 750px,则 rootValue应为 75,所以可以这样写:


rootValue({ file }) {
    return file.indexOf('hxb2b') !== -1 ? 37.5 : 75;
}

unitPrecision(Number) 生成的rem单位保留的小数点位数;

selectorBlackList(Array) 要忽略的选择器并保留为px,可以是字符串或正则表达式,比如['body','/^body$/'];

propList(Array) 是一个存储哪些将被转换的属性列表,比如 ['font', 'font-size', 'line-height', 'letter-spacing']。这里设置为['*']全部,假设需要仅对边框进行设置,可以写['*', '!border*']

replace(Boolean) 替换包含rems的规则;

mediaQuery(Boolean) 允许在媒体查询中转换px;

minPixelValue(Number) 所有小于设置此数值的样式都不被转换;

exclude(String,Regexp,Function) 要忽略并保留为px的文件路径;

  1. 注意:
  • 如果写的是行内样式,则不会进行转换;

<div style="width:250px"></div>
  • 设置的样式中某个元素想要使用px并且不想被转换,可以只用Px

.container{
    width:375Px; //不会被转换
    height:375px; //转换为10rem
}
posted @ 2025-05-19 22:54  Justus-  阅读(70)  评论(0)    收藏  举报