移动端自适应优雅布局

456 阅读1分钟

移动端自适应优雅布局

最早开发h5页面的时候,会引入一段自适应的js代码来进行自适应布局。或者scss媒体查询、根据页面宽度更改html根元素的字体大小。然后在页面的布局中按照自己设置的比例,根绝设计图,计算出对应的rem值。

然鹅。现在已经0202年了。这种方式早已out。 如果可以,我们只需要按照设计图写出px值,rem的转换,交给其他工具来做。这样是不是方便很多呢?接下来给大家分享一下如何优雅自适应。以vue-cli项目为例

  • 首先在你的项目中安装amfe-flexible,postcss-pxtorem。
$ npm i -D postcss-pxtorem// 等同于npm install pxtorem --save-dev
$ npm i -S amfe-flexible //等同于npm install -save amfe=flexible
  • 接着在main.js或者main.ts文件中引入amfe-flexible
import 'amfe-flexible'

amfe-flexible引入后刷新页面,可以发现,此时根元素(html)的font-size已经变成此时屏幕的宽度(/10)的十分之一

  • 在src目录下面新建一个postcss.config.js文件。或者可以直接加载package.json文件中
// postcss.config.js
module.exports = {
  plugins: {
    autoprefixer: {
      overrideBrowserslist: ['Android >= 4.0', 'iOS >= 7']
    },
    'postcss-pxtorem': {
      rootValue: 37.5,
      propList: ['*']
    }
  }
}

// package.json
 "postcss": {
    "plugins": {
      "autoprefixer": {
        "overrideBrowserslist": [
          "Android >= 4.0",
          "iOS >= 7"
        ]
      },
      "postcss-pxtorem": {
        "rootValue": 37.5,
        "propList": ["*" ]
      }
    }
  },

rootValue属性值为你拿到的设计图的尺寸除以10,比如我的设计图是375px(iphone6的尺寸),我就把值设置为37.5。propList是需要转换的属性,*代表全部css属性都要转成rem。postcss-pxtorem的具体参数可参照文档 postcss-pxtorem