—— 网页开发中的安全区域适配指南
在 iPhone X 及后续全面屏机型上,网页底部常出现一块“灰色区域”或“空白条”,这是由于 iOS 为手势操作保留的安全区域(Safe Area)。许多开发者误以为是 bug,其实它是系统设计的一部分。
本文将解释其成因,并提供实用的 HTML/CSS 解决方案,帮助你完全控制页面布局。
从 iPhone X 开始,苹果引入了“Home Indicator”(底部小白条),用于返回主屏幕。为避免网页内容被遮挡或误触,Safari 默认在视口(viewport)中预留了安全边距(safe area inset)。
如果你的页面背景是纯色或图片,底部就会露出一块“灰色”(实际是系统默认背景色)。
viewport-fit=cover在 HTML 的 <head> 中设置 viewport 元标签:
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
这行代码告诉浏览器:**允许内容延伸到整个屏幕,包括安全区域**。
即使设置了 viewport-fit=cover,你也应使用 CSS 环境变量来确保重要内容不被遮挡:
body {
padding-bottom: env(safe-area-inset-bottom);
}
或者,如果你想让背景色/图片铺满到底部,可这样写:
body {
background: #007aff;
min-height: 100vh;
padding-bottom: env(safe-area-inset-bottom);
}
这样既能填满灰色区域,又保证交互元素不会被手势条覆盖。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
<title>无灰色区域页面</title>
<style>
body {
margin: 0;
background: linear-gradient(to bottom, #ff9a9e, #fad0c4);
min-height: 100vh;
padding-bottom: env(safe-area-inset-bottom);
}
</style>
</head>
<body>
<h1>Hello iPhone!</h1>
</body>
</html>
env(safe-area-inset-*) 在非支持设备上会自动忽略,无需担心兼容性。