1. 安装 postcss-pxtorem 和 autoprefixer
npm install postcss-pxtorem autoprefixer --save
2. vite.config.js引入并配置
import postCssPxToRem from 'postcss-pxtorem'
import autoprefixer from 'autoprefixer'
export default defineConfig({
base: './',
resolve: {
alias
},
plugins: [vue()],
css: {
postcss: {
plugins: [
postCssPxToRem({
rootValue: 16,
propList: ['*'],
}),
autoprefixer({
overrideBrowserslist: [
"Android 4.1",
"iOS 7.1",
"Chrome > 31",
"ff > 31",
"ie >= 8"
],
grid: true
})
]
}
}
})
4. 在根目录src下建立文件夹utils,然后创建rem.js文件 并在main.js中引入
const baseSize = 16;
function resize() {
let scale = document.documentElement.clientWidth / 1920;
if (document.documentElement.clientWidth < 1280) scale = 1280 / 1920
document.documentElement.style.fontSize = `${baseSize * Math.min(scale, 1)}px`;
}
resize();
window.onresize = resize;
function resize() {
let fs = document.body.clientWidth / 75;
if (fs > 16) {
fs = 16;
} else if (fs < 14) {
fs = 14;
}
document.body.parentNode.style = "font-size: " + fs + "px;";
}
resize();
window.onresize = resize;
import './utils/rem.js'
<template>
<div id="app">
</div>
</template>
<script setup>
function resize() {
let fs = document.body.clientWidth / 75;
if (fs > 16) {
fs = 16;
} else if (fs < 14) {
fs = 14;
}
document.body.parentNode.style = "font-size: " + fs + "px;";
}
resize();
window.onresize = resize;
</script>