移动端布局postcss-px-to-viewport

429 阅读1分钟

移动端自适应大家肯定第一时间想到rem布局 但是由于本人对postcss-pxtorem的rootValue理解不够透彻 (我真的花了很长时间去搞明白这个属性,但是还是无法理解这个东西到底怎么去换算的),于是查阅资料,这里记录一下另外一种移动端适配方案:post-css-to-viewport。

1.我们先把它安装到项目的开发环境中: npm i postcss-px-to-viewport -D

2.在项目根目录下添加.postcssrc.js文件 3.添加如下配置:

const path = require('path');

module.exports = ({ file }) => {
  const designWidth = file.dirname.includes(path.join('node_modules', 'vant')) ? 375 : 750;

  return {
    plugins: {
    autoprefixer: {}, // 用来给不同的浏览器自动添加相应前缀,如-webkit-,-moz-等等
    "postcss-px-to-viewport": {
      unitToConvert: "px", // 要转化的单位
      viewportWidth: designWidth, // UI设计稿的宽度
      //viewportHeight: 1080, // 视窗的高度,根据750设备的宽度来指定,一般指定1334,也可以不配置
      unitPrecision: 6, // 转换后的精度,即小数点位数
      propList: ["*"], // 指定转换的css属性的单位,*代表全部css属性的单位都进行转换
      viewportUnit: "vw", // 指定需要转换成的视窗单位,默认vw
      fontViewportUnit: "vw", // 指定字体需要转换成的视窗单位,默认vw
      selectorBlackList: [".wrap", ".el-], // 指定不转换为视窗单位的类名,
      minPixelValue: 1, // 默认值1,小于或等于1px则不进行转换
      mediaQuery: true, // 是否在媒体查询的css代码中也进行转换,默认false
      replace: true, // 是否转换后直接更换属性值
      exclude: [], // 设置忽略文件,用正则做目录名匹配
      landscape: false // 是否处理横屏情况
    }
  }
  }

}