响应式与移动端适配
响应式与移动端适配的考点是一条链:viewport meta 声明视口 → 相对单位(rem/vw/%)替代固定 px → 媒体查询按断点切换布局 → 移动端细节(1px 边框、安全区、44px 命中区域)。核心思想是“内容像水”,同一套代码适配多种屏幕。
面试爱问“1px 边框”与“rem 适配”:1px 问题的本质是 CSS 像素与物理像素的换算(DPR=2 时 CSS 1px 用 2 个物理像素渲染,显得粗),通用解法是伪元素 scaleY(0.5);rem 适配是一段按屏宽改根字号的 JS,配合设计稿换算实现整页等比还原。
- 链路:viewport → 相对单位 → 媒体查询 → 移动端细节(1px / 安全区 / 命中区)
- 1px 边框 = 伪元素 scaleY(0.5);rem 适配 = 按屏宽改根字号
- 移动优先写法:默认小屏样式,min-width 逐级增强
HTML
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <!-- 第一步永远是它:否则手机按 980px 宽渲染再整体缩小 --> <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover"> <style> /* 相对单位 + 自动列数:无媒体查询的自适应卡片 */ .cards { display: grid; gap: 12px; padding: 12px; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); } .card { padding: 16px; border: 1px solid #eee; border-radius: 8px; } /* 1px 边框:伪元素缩放 */ .hairline { position: relative; } .hairline::after { content: ''; position: absolute; left: 0; right: 0; bottom: 0; height: 1px; background: #ddd; transform: scaleY(0.5); } /* 安全区:env() 避开刘海与手势条 */ .footer { position: fixed; left: 0; right: 0; bottom: 0; padding: 12px 16px; padding-bottom: max(12px, env(safe-area-inset-bottom)); background: #fff; border-top: 1px solid #eee; } </style> </head> <body> <div class="cards"> <div class="card hairline">A</div> <div class="card">B</div> <div class="card">C</div> </div> <div class="footer">底部固定栏</div> <script> // rem 适配:设计稿 375 宽时 1rem = 100px document.documentElement.style.fontSize = innerWidth / 3.75 + 'px'; </script> </body> </html>
本节要点响应式链路:viewport → 相对单位 → 媒体查询;移动端三细节:1px 缩放、env 安全区、44px 命中区。




