前言
安全区域与边界是iOS11 新增特性。
安全区域
安全区域的内容不受圆角(corners)、齐刘海(sensor housing)、小黑条(Home Indicator)影响。
Webkit 为此增加了相应的CSS 函数(env, constant)用于获取安全区域边界值。
安全区域边界
安全区域边界有4个预定义变量:
safe-area-inset-left:安全区域距离左边边界距离
safe-area-inset-right:安全区域距离右边边界距离
safe-area-inset-top:安全区域距离顶部边界距离
safe-area-inset-bottom:安全区域距离底部边界距离
获取安全区域边界的方法
env(safe-area-inset-bottom)
最佳实践
body {
padding-bottom: calc( constant(safe-area-inset-bottom) + 150rpx); /* 兼容 iOS < 11.2 */
padding-bottom: calc( env(safe-area-inset-bottom) + 150rpx); /* 兼容 iOS >= 11.2 */
}
/* 兼容老的连constant都不支持的ios机型 */
@supports not(constant(safe-area-inset-bottom)){
page {
padding-bottom: 150rpx;
}
}
注意:constant在前,env在后。
常用场景:
设置底部安区域背景色
步骤 1: 获取底部安全区域的高度
要获取底部安全区域的高度,我们可以使用JavaScript代码。下面是获取底部安全区域高度的代码:
const safeAreaHeight = window.innerHeight - document.documentElement.clientHeight;
步骤 2: 创建一个容器元素
在HTML中,我们需要创建一个容器元素来承载底部安全区域的背景色。可以使用一个div元素来作为容器元素:
<div id="safeAreaContainer"></div>
步骤 3: 设置容器元素的样式
使用CSS来设置容器元素的样式,包括位置、宽度等。下面是设置容器元素样式的代码:
#safeAreaContainer {
position: fixed;
left: 0;
bottom: 0;
width: 100%;
}
步骤 4: 设置容器元素的高度为底部安全区域的高度
将步骤 1 中获取到的底部安全区域的高度应用到容器元素的高度上:
const safeAreaHeight = window.innerHeight - document.documentElement.clientHeight;
document.getElementById('safeAreaContainer').style.height = safeAreaHeight + 'px';
步骤 5: 设置容器元素的背景色
最后一步是设置容器元素的背景色。我们可以在CSS中设置背景色的值为我们想要的颜色:
#safeAreaContainer {
background-color: #f2f2f2;
}
设置头部安区域背景色
原理同上