一、主流移动端适配方案
1. 视口meta标签 (基础必备)
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
2. 媒体查询 (Media Queries)
/* 小屏幕设备 */
@media only screen and (max-width: 375px) {
.box {
width: 100%;
}
}
/* 中等屏幕设备 */
@media only screen and (min-width: 376px) and (max-width: 414px) {
.box {
width: 80%;
}
}
3. Flex 弹性布局
.container {
display: flex;
justify-content: space-between;
flex-wrap: wrap;
}
4. Grid 网格布局
.container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
}
二、REM适配方案 (核心方案)
1. 基本原理
-
rem (root em) 是基于根元素(html)字体大小的单位
-
通过动态设置html的font-size实现整体缩放
2. 经典实现方案
方案一:基于设计稿宽度(推荐)
// 假设设计稿宽度为750px
document.documentElement.style.fontSize =
(document.documentElement.clientWidth / 7.5) + 'px';
// 使用时:设计稿上100px → 1rem
方案二:基于屏幕比例
(function() {
const baseSize = 16; // 基准大小(px)
const scale = document.documentElement.clientWidth / 375; // 375为设计稿宽度
document.documentElement.style.fontSize =
(baseSize * Math.min(scale, 2)) + 'px'; // 限制最大缩放比例
})();
3. 现代CSS方案:使用calc()+vw
/* 不需要JS,纯CSS解决方案 */
html {
font-size: calc(100vw / 7.5); /* 750设计稿 → 100px = 1rem */
}
三、字体大小适配策略
1. REM适配字体
body {
font-size: 0.16rem; /* 相当于16px(当html font-size为100px时) */
}
h1 {
font-size: 0.24rem; /* 24px */
}
2. 媒体查询调整字体
html {
font-size: 14px;
}
@media screen and (min-width: 320px) {
html {
font-size: calc(14px + 2 * (100vw - 320px) / 55); /* 320-375px渐变 */
}
}
@media screen and (min-width: 375px) {
html {
font-size: 16px;
}
}
3. 限制字体最大最小值
body {
font-size: clamp(12px, 1.5vw, 16px); /* 最小值12px,理想值1.5vw,最大值16px */
}
四、PX转REM工作流
1. Webpack + postcss-pxtorem
// postcss.config.js
module.exports = {
plugins: {
'postcss-pxtorem': {
rootValue: 16, // 基准值
propList: ['*'], // 需要转换的属性
selectorBlackList: [/^html$/], // 不转换html的font-size
}
}
}
2. Vite方案
// vite.config.js
import pxtorem from 'postcss-pxtorem';
export default {
css: {
postcss: {
plugins: [
pxtorem({
rootValue: 16,
propList: ['*'],
})
]
}
}
}
3. VS Code插件辅助
-
px to rem 插件:在编辑器中快速转换
-
配置快捷键实现一键转换
五、最佳实践建议
-
设计稿基准:以iPhone6/7/8(375px)或通用750px宽度为设计基准
-
REM基准值:建议设置1rem=16px(默认)或1rem=100px(方便计算)
-
字体处理:
-
正文使用rem保证可缩放
-
标题可以使用vw单位实现视口响应
-
使用clamp()限制字体大小范围
-
-
边界情况:
// 防止字体过大 window.addEventListener('resize', () => { const fontSize = document.documentElement.clientWidth / 7.5; document.documentElement.style.fontSize = Math.min(fontSize, 100) + 'px'; // 限制最大100px });
-
1px边框问题:
.border-1px { position: relative; } .border-1px::after { content: ""; position: absolute; bottom: 0; left: 0; right: 0; height: 1px; background: #000; transform: scaleY(0.5); transform-origin: 0 0; }
六、现代替代方案:Viewport单位
1. 纯vw方案
/* 750设计稿 → 100px = 13.333vw (100/750*100) */
.box {
width: 13.333vw;
height: 13.333vw;
}
2. vw + rem混合方案
html {
font-size: calc(100vw / 7.5);
}
.box {
width: 1rem; /* 相当于100px */
}
选择建议:中小型项目可以使用纯REM方案,大型复杂项目建议采用REM+媒体查询的组合方案。