基于高度(vh)+ 基于宽度(vw)混合方案
纵向属性 → vh(基于高度 812px)
横向属性 → vw(基于宽度 375px,由 postcss 自动转换)
以下页面使用内联样式,需要手动改造:
.element {
top: 138px; /* → 36.8vw (基于宽度)❌ */
left: 45px; /* → 12vw ✅ */
width: 245px; /* → 65.33vw ✅ */
height: 113px; /* → 30.13vw ❌ */
}
.element {
top: 17vh; /* 138 / 812 × 100 = 17vh ✅ */
left: 45px; /* → 12vw (自动转换) ✅ */
width: 245px; /* → 65.33vw (自动转换) ✅ */
height: 13.92vh; /* 113 / 812 × 100 = 13.92vh ✅ */
}
// 纵向属性(手动计算)
vh = (设计稿px / 812) × 100
// 横向属性(保持 px,自动转换)
vw = (设计稿px / 375) × 100 // postcss 自动处理
import { px2vw } from '@/utils/viewport';
<div style={{
top: px2vw(138), // ❌ 基于宽度
left: px2vw(45), // ✅ 正确
width: px2vw(245), // ✅ 正确
height: px2vw(113), // ❌ 基于宽度
}}>
import { px2vw, px2vh } from '@/utils/viewport';
<div style={{
top: px2vh(138), // ✅ 基于高度
left: px2vw(45), // ✅ 基于宽度
width: px2vw(245), // ✅ 基于宽度
height: px2vh(113), // ✅ 基于高度
}}>
topbottomheightmin-heightmax-heightpadding-toppadding-bottommargin-topmargin-bottomline-height (特殊:建议用 vh)gap (垂直方向)leftrightwidthmin-widthmax-widthpadding-leftpadding-rightmargin-leftmargin-rightgap (水平方向)font-size - 保持使用 vw(基于宽度更合理)border-radius - 保持使用 vw(基于宽度)box-shadow - 保持 px(不需要缩放)设计稿: top: 138px, left: 45px, width: 245px, height: 113px
.welcome-hello {
position: absolute;
top: 17vh; /* 138 / 812 = 17% */
left: 45px; /* → 12vw (自动) */
width: 245px; /* → 65.33vw (自动) */
height: 13.92vh; /* 113 / 812 = 13.92% */
}
设计稿: height: 56px
.register-input {
height: 6.9vh; /* 56 / 812 = 6.9% */
border-radius: 12px; /* → 3.2vw (自动) */
}
// ❌ 改造前
<div style={{
height: px2vw(layout.avatarSize),
marginTop: px2vw(layout.avatarMarginTop),
}}>
// ✅ 改造后
<div style={{
height: px2vh(layout.avatarSize),
marginTop: px2vh(layout.avatarMarginTop),
}}>
vw 方案: 700px → 186.67vw → 700px ❌ 超出屏幕
vh 方案: 700px → 86.2vh → 575px ✅ 自动适配
vw 方案: 700px → 186.67vw → 700px ✅ 符合设计稿
vh 方案: 700px → 86.2vh → 700px ✅ 完全符合设计稿
vw 方案: 700px → 186.67vw → 733px ⚠️ 可能超出
vh 方案: 700px → 86.2vh → 798px ✅ 按比例放大
改造重点:
layout.avatarSize - 改用 px2vhlayout.avatarMarginTop - 改用 px2vhlayout.buttonBottomPosition - 改用 px2vh改造重点:
contentPaddingTop - 改用 px2vhcontentPaddingBottom - 改用 px2vhsectionGap - 改用 px2vhlineHeight - 改用 px2vh改造重点:
改造重点:
改造完成后,在以下设备上测试:
重点检查:
A: 宽度变化小(375-393px),高度变化大(667-926px)。纵向用 vh 更合理。
A: 如果使用了 clamp(min, preferred, max),preferred 值改为 vh:
/* 改造前 */
top: clamp(56px, 7vh, 64px);
/* 改造后(如果需要更严格) */
top: 6.9vh; /* 56 / 812 = 6.9vh */
A:
100% - 相对父元素100vh - 相对视口高度100vh 更可靠| 设计稿值 | vh 计算 | 结果 |
|---|---|---|
| 56px | 56 / 812 × 100 | 6.9vh |
| 138px | 138 / 812 × 100 | 17vh |
| 700px | 700 / 812 × 100 | 86.2vh |
在线计算器: (设计稿px / 812) × 100 = vh