til / Safely position fixed content on newer mobile devices
If we want to position fixed content safely on a mobile device that has a notch and/or a home bar, such as the iPhone X or iPhone 12, we need to take into account the safe area of the device. This is especially important if we have interactive elements, such as links or buttons, in the content. Luckily, there’s a CSS function that can help us!
Let’s say we’re creating a cookie consent that contains a link.
<div class="cookie-consent">
<p>By using this app you consent to our usage of cookies.</p>
<a href="#">I understand</a>
</div>
.cookie-consent {
background-color: #fff;
bottom: 0px;
left: 0px;
padding: 20px;
position: fixed;
right: 0px;
}
If we don’t add any specific spacing the link would fall below the safe area when scrolled and it wouldn’t be clickable.
The padding needed to move the content above the safe area can vary between devices, but here’s where the magic CSS function comes to the rescue. We just need one line to fix this on every device:
.cookie-consent {
/* Previous content... */
padding-bottom: calc(env(safe-area-inset-bottom) + 20px);
}
There’s also
safe-area-inset-top
,safe-area-inset-right
, andsafe-area-inset-left
if you have content that needs to be adjusted for other directions
This uses environment variables, safe-area-inset-bottom
in this case, that are provided in the browser and adds that to the padding we already had.
The browser support for this is very good and it should be supported on all devices that require the adjustment.