postcss-pxtorem实现移动端适配

647 阅读1分钟

一、使用到的插件

(1)amfe-flexible amfe-flexible是配置可伸缩布局方案,主要是将1rem设为viewWidth/10

(2)postcss-pxtorem postcss-pxtorem是一款将px转换成rem格式的方式,本质上是以html标签的fontsize值为基准,动态改变元素的各种计量单位。

二、插件的安装和使用

1.安装

  1. npm i amfe-flexible -s
  2. npm i postcss-pxtorem@5.1.1 (建议使用这个版本)

2.使用

(1)在main.js导入amfe-flexible,import 'amfe-flexible'

(2)配置postcss-pxtorem,可在vue.config.js、.postcssrc.js、postcss.config.js其中之一配置,权重从左到右降低,没有则新建文件,只需要设置其中一个即可: 在vue.config.js配置如下:

module.exports = {
    //...其他配置
    css: {
        loaderOptions: {
            postcss: {
                plugins: [
                    require('postcss-pxtorem')({
                        rootValue: 37.5,
                        propList: ['*']
                    })
                ]
            }
        }
    },
}

在.postcssrc.js或postcss.config.js中配置如下:

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

rootValue根据设计稿宽度除以10进行设置,这边假设设计稿为375,即rootValue设为37.5(根据设计稿来确定) propList是设置需要转换的属性,这边*表示所有都进行转换

三、解决移动端1px问题

解决移动端1px显示问题(index.html),在index里配置加上

<meta name="viewport" content="width=device-width,initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">