vue3 pc端移动端rem自适应布局

1,024 阅读1分钟

1. 安装依赖


npm install amfe-flexible // CSS单位自适应转换插件 负责更改根font-size
npm install postcss-pxtorem@^5.1.1 // 如果版本过高可以降版本下载5.1.1版本 负责将px转成rem

2. 引入amfe-flexible

在main.js中引入amfe-flexible

import "amfe-flexible"

3. 配置vite.config.js

import postCssPxToRem from 'postcss-pxtorem'

export default defineConfig(({ mode }) => {
  return {
    css: {
      postcss: {
        plugins: [
          autoprefixer({
            overrideBrowserslist: [
              'Android 4.1',
              'iOS 7.1',
              'Chrome > 31',
              'ff > 31',
              'ie >= 8'
            ]
          }),
          postCssPxToRem({
            // 自适应,px>rem转换
            rootValue: 192, // 75表示750设计稿,37.5表示375设计稿
            propList: ['*'] // 需要转换的属性,这里选择全部都进行转换
            // selectorBlackList: ['norem'], // 过滤掉norem-开头的class,不进行rem转换
            // unitPrecision: 5, //允许rem单位增长的十进制数字
            // replace: true, //替换包含rems的规则,而不添加后备
            // mediaQuery: false, //允许在媒体查询中转换px
            // minPixelValue: 0, //设置要替换的最小像素值
            // selectorBlackList: [], //忽略转换正则匹配项
            // exclude: /node_modules/i //要忽略并保留为px的文件路径
          })
        ]
      }
    }
  }
})