Home Writing Reading

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.

User hasn't scrolled and the link is clickable The user hasn't scrolled, link is clickable.
User has scrolled and the link is below the safe area and not clickable Scrolled, link is below safe area and not 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);
}
User hasn't scrolled and the link is clickable The user hasn't scrolled, link is clickable.
User has scrolled and the link is above the safe area and is clickable Scrolled, link is above safe area and is clickable.

There’s also safe-area-inset-top, safe-area-inset-right, and safe-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.


  • Loading next post...
  • Loading previous post...