For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /blog/mobile/vant-rem.md.

Vant UI rem 适配

Vant UI 组件库的样式默认使用的单位是 px,若需要使用 rem,则需要使用插件进行进一步的处理

转换工具

插件安装

npm
yarn
pnpm
bun
deno
npm install postcss-pxtorem -D
npm
yarn
pnpm
bun
deno
npm install lib-flexible -S

PostCSS 配置

postCss 配置
const autoprefixer = require("autoprefixer");
const pxtorem = require("postcss-pxtorem");

module.exports = {
    publicPath: "/",
    outputDir: "dist",
    /* PostCSS 配置 */
    css: {
        loaderOptions: {
            postcss: {
                plugins: [
                    autoprefixer({
                        browsers: ["Android >= 4.0", "iOS >= 8"],
                    }),
                    pxtorem({
                        rootValue: 37.5,
                        propList: ["*"],
                    }),
                ],
            },
        },
    },
    devServer: {
        open: true,
        // proxy: ""
    },
    productionSourceMap: false,
};

Rem 基准值设置

  • 在入口文件 main.js 顶部添加 import"amfe-flexible";

CSS 样式编写

根字体大小默认 37.5px,故 1rem = 37.5px。若移动端参照 2 倍 750 宽度设计图,则编写的样式可以采用 rem 相对单位按照 1rem = 37.5px 宽度进行换算,也可以使用 px 像素 / 2 作为设计图元素的宽度。亦或者将 2 倍图调整为 1 倍 375 宽度设计图,按照 1:1 的比例进行样式的调整。