0
点赞
收藏
分享

微信扫一扫

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

生活记录馆 2022-04-06 阅读 82
vue.js前端

1.安装lib-flexible

yarn add lib-flexible

2.引入lib-flexible

# src/main.ts

import 'lib-flexible/flexible'

3.安装postcss-pxtorem

yarn add lib-flexible

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 postcss-pxtorem@5.1.1 

原理

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

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

举报

相关推荐

0 条评论