移动端rem适配布局:Vue+amfe-flexible+postcss-pxtorem

rem(root em)是一个相对单位,基准是相对于html元素的字体大小(浏览器默认字体大小是16px)。如:根元素(html)设置font-size: 12px;  非根元素设置width: 2rem; 则换成px表示就是24px。

amfe-flexible:原理是把当前设备宽度划分为10等份,动态设置html元素的字体大小为一份。如:当前屏幕宽度为360px,html元素的字体大小为36px。

postcss-pxtorem:不同设备下,元素占比是一定的,即rem的值不变。此工具自动将px转成rem。

步骤:

1、安装

npm install amfe-flexible --save
npm install postcss-pxtorem --save

2、main.js中导入amfe-flexible

import 'amfe-flexible'

3、配置postcss-pxtorem,可在.postcssrc.js文件配置

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

其中:

  • rootValue:根据设计稿除以10进行配置。如:设计稿是750,rootValue即为75。若此时引入了mint-ui等UI库,当屏宽为750时1:1还原mint-ui的组件,但相对于整个页面来说组件偏小。此时,rootValue设为37.5,用375的设计稿开发,效果基本满足。
  • propList:[Array],设置需要转换的属性。['*']:转换全部属性。['*', '!letter-spacing']:转换除letter-spacing外的全部属性。

4、CSS代码

.test {
  font-size: 37.5px; /* converted to 1rem */
}

5、浏览器的效果

  • html的字体大小是屏宽的1/10
  • css代码中的px自动转换为rem

6、tips

  • 不进行rem转换,最直接的方式是使用Px或PX。
.ignore {
    border: 1Px solid; // ignored
    border-width: 2PX; // ignored
}

    另:postcss-pxtorem有多种参数配置方式,可忽略转换,请自行学习。

  • amfe-flexible自动计算html的字体大小。对于超过750px的屏宽,按750处理,同时设置font-size为75px。
body {
   min-width: 320px;
   max-width: 750px;
   width: 10rem;
   margin: 0 auto;
}
@media screen and (min-width: 750px) {
  html {
    font-size: 75px !important;
  }
}

The End

猜你喜欢

转载自blog.csdn.net/weixin_43932309/article/details/125102930