1最经典也最稳定的自适应方式媒体查询-media,通过 CSS 设置不同屏幕下的样式:
✔️ 优点:兼容性好,灵活
❌ 缺点:代码量大,维护成本高
/* 手机 */
@media screen and (max-width: 768px) {
body {
font-size: 14px;
}
}
/* 平板 */
@media screen and (min-width: 769px) and (max-width: 1024px) {
body {
font-size: 16px;
}
}
/* PC */
@media screen and (min-width: 1025px) {
body {
font-size: 18px;
}
}
🧩 三、vw
/ vh
单位(现代浏览器 ✅)
- 概述:这名字一听就麻烦,具体方法为获得 rem 的基准值 ,动态的计算
html根元素的font-size
,图表中通过 vw vh 动态计算字体、间距、位移等 1rem
的真实像素值是由html
根元素的font-size
决定的。- font-size等于1rem相当于 font-size=16px,1rem=16px
-
<style> html { font-size: 100px; } .box { width: 2rem; /* 实际宽度是 2 × 100 = 200px */ height: 1rem; /* 实际高度是 1 × 100 = 100px */ } </style>
✔️ 优点:不用 JS,纯 CSS
❌ 缺点:旧浏览器支持差、不方便控制精度
-
1vw
= 视口宽度的 1% -
1vh
= 视口高度的 1% -
.container { width: 90vw; height: 60vh; font-size: 2vw; } //概述:按照设计稿的尺寸,将px按比例计算转为vw和vh //优点:可以动态计算图表的宽高,字体等,灵活性较高,当屏幕比例跟 ui 稿不一致时,不会出现两边留白情况 //缺点:每个图表都需要单独做字体、间距、位移的适配,比较麻烦
-
✅ 一、scale 方案核心原理
-
将整个页面的内容包裹在一个容器中,通过 JS 获取浏览器窗口的尺寸比例,然后使用
transform: scale()
缩放整个页面。🧱 示例结构:
html, body { width: 100%; height: 100%; margin: 0; overflow: hidden; } #app { width: 1920px; height: 1080px; transform-origin: left top; }
function scalePage() { const scaleX = window.innerWidth / 1920; const scaleY = window.innerHeight / 1080; const scale = Math.min(scaleX, scaleY); // 保证缩放不超出可视区域 const app = document.getElementById('app'); app.style.transform = `scale(${scale})`; } window.addEventListener('resize', scalePage); scalePage(); // 初始化时调用
二、autofit.js 自动处理 scale + 热区问题
- ①+
npm install @jiaminghi/autofit
②
import autofit from '@jiaminghi/autofit'; autofit.init({ width: 1920, height: 1080, el: '#app', // 容器 id });
autofit.init({
width: 1920,
height: 1080,
el: '#app',
delay: 100, // resize 时节流
mode: 'contain', // 可选:'contain' / 'cover'
});
export default {
mounted() {
autofit.init({
dh: 1080,
dw: 1920,
el:"body",
resize: true
})
},
}
最新版 v3.2.x 支持更多功能,请访问:auto-plugin.github.io/autofit.js/
三 插件将 px 转成 rem,常与 postcss.config.js
或
. 📦 postcss-px-to-viewport
将 px 转换成
vw
单位(响应式自动缩放)npm i postcss-pxtorem -D
// postcss.config.js
module.exports = {
plugins: {
'postcss-pxtorem': {
rootValue: 100, // 设计稿宽度为1920时建议100
propList: ['*'], // 所有属性都转
exclude: /node_modules/i,
},
},
};②②
②npm install postcss-px-to-viewport -D// postcss.config.js
module.exports = {
plugins: {
'postcss-px-to-viewport': {
viewportWidth: 1920, // 设计稿宽度
unitPrecision: 3,
viewportUnit: 'vw',
selectorBlackList: ['ignore'], // 类名含 ignore 的不转
minPixelValue: 1,
mediaQuery: false,
},
},
};