方案一:REM 布局 + 动态基准字体大小(推荐)
通过 PostCSS 将 px 转换为 rem,并根据屏幕宽度动态调整根元素字体大小,实现等比缩放。
步骤 1:安装依赖
pnpm add -D postcss postcss-pxtorem @unocss/postcss
步骤 2:配置 PostCSS(postcss.config.js
)
module.exports = {
plugins: [
'@unocss/postcss', // 处理 UnoCSS 规则
[
'postcss-pxtorem', // px → rem 转换
{
rootValue: 16, // 基准字体大小(设计稿为 16px 时的 rem 计算基准)
propList: ['*'], // 转换所有属性
exclude: /node_modules/i, // 排除 node_modules
},
],
],
}
步骤 3:添加动态字体大小脚本
在入口 HTML 文件中添加 JS 代码,根据屏幕宽度动态计算根字体大小:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>UnoCSS 适配示例</title>
<script>
// 基准设计稿宽度(如 1920px 桌面端或 375px 移动端)
const baseWidth = 1920;
// 基准字体大小(对应设计稿宽度的根字体大小)
const baseFontSize = 16;
function setRemUnit() {
const width = Math.min(window.innerWidth, 1920); // 最大宽度限制
const rem = (width / baseWidth) * baseFontSize;
document.documentElement.style.fontSize = `${rem}px`;
}
// 初始化
setRemUnit();
// 窗口大小变化时重新计算
window.addEventListener('resize', setRemUnit);
</script>
</head>
<body>
<!-- 页面内容 -->
</body>
</html>
步骤 4:配置 UnoCSS 响应式断点
// uno.config.ts
import { defineConfig } from 'unocss'
export default defineConfig({
theme: {
breakpoints: {
sm: '640px', // 小屏幕
md: '768px', // 平板
lg: '1024px', // 桌面
xl: '1280px', // 大屏幕
},
},
})
效果
- 设计稿中
16px
→ 自动转换为1rem
- 屏幕宽度变化时,根字体大小动态调整,所有 rem 单位元素等比缩放
- 结合 UnoCSS 响应式类(如
md:text-lg
)进一步优化布局