vue移动端适配方案 - px 自动转 rem

1.安装lib-flexible

yarn add lib-flexible

2.引入lib-flexible

# src/main.ts

import 'lib-flexible/flexible'

3.安装postcss-pxtorem

yarn add postcss-pxtorem

4.在根目录下新建 postcss.config.js

# project_name/postcss.config.js

module.exports = {
    plugins: {
    // 兼容浏览器,添加前缀
    autoprefixer: {
        overrideBrowserslist: [
          "Android 4.1",
          "iOS 7.1",
          "Chrome > 31",
          "ff > 31",
          "ie >= 8",
          "last 10 versions",
        ],
        grid: true,
      },
      "postcss-pxtorem": {
        //rootValue: 16,//结果为:设计稿元素尺寸/16,比如元素宽320px,最终页面会换算成 20rem
        rootValue: 75, //通常结合 lib-flexible 设置 rem 基准值,默认用75,不然容易出问题
        propList: ["*"], // 需要做转化处理的属性,如`hight`、`width`、`margin`等,`*`表示全部
        unitPrecision: 5, //保留rem小数点多少位
        replace: true,
        mediaQuery: false, //媒体查询( @media screen 之类的)中不生效
        minPixelValue: 12, //px小于12的不会被转换
      }
    }
  }

嫌麻烦的可以换成下面这样:

module.exports = {
  plugins: {
    autoprefixer: {},
    "postcss-pxtorem": {
      "rootValue": 75,
      "propList": ['*'],
    }
  }
}

重启项目即可

如果在运行项目中出现如下报错信息:

vue Syntax Error: Error: PostCSS plugin postcss-pxtorem requires PostCSS 8.

检查package.jso中postcss-pxtorem的版本,如果是6.*则是版本过高不兼容问题,卸载重装5.1.1版本的即可。

yarn remove postcss-pxtorem
yarn add [email protected] 

原理

lib-flexible: 根据不同的屏幕算出html的font-size,通过js来动态写meta标签。会自动在html的head中添加一个meta name="viewport"的标签,同时会自动设置html的font-size为屏幕宽度除以10,也就是1rem等于html根节点的font-size。假如设计稿的宽度是750px,此时1rem应该等于75px。假如量的某个元素的宽度是150px,那么在css里面定义这个元素的宽度就是 width: 2rem

注意:
1.lib-flexible会为页面根据屏幕自动添加<meta name='viewport' >标签,动态控制initial-scale,maximum-scale,minimum-scale等属性的值。
2.检查一下html文件的head中,如果有 meta name="viewport"标签,需要将他注释掉,因为如果有这个标签的话,lib-flexible就会默认使用这个标签。而我们要使用lib-flexible自己生成的 meta name="viewport"来达到高清适配的效果。
3.因为html的font-size是根据屏幕宽度除以10计算出来的,所以我们需要设置页面的最大宽度是10rem。
4.如果每次从设计稿量出来的尺寸都手动去计算一下rem,就会导致我们效率比较慢,还有可能会计算错误,所以我们可以使用postcss-pxtorem或者postcss-px2rem-exclude自动将css中的px转成rem

postcss-pxtorem: 自动将项目中的 px 转为 rem

注意:
1.postcss-pxtorem会将px转换为rem用于适配不同宽度的屏幕,根据<html>标签的font-size值来计算出结果,即1rem=html标签的font-size值。
2.对于行内样式,postcss-pxtorem并不能将px转rem,所以对于需要自适应的样式,如font-size、width、height等请不要写在行内。同理,对于不需要转化的样式可以写在行内,或者使用PX(大写)作为单位。
3.如果在.vue文件style中的某一行代码不希望被转成rem,只要在后面写上注释 /* no*/就可以了

猜你喜欢

转载自blog.csdn.net/weekdawn/article/details/123993919