DEV Community

Rickard Natt och Dag
Rickard Natt och Dag

Posted on • Originally published at willcodefor.beer on

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 property 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>


Enter fullscreen mode Exit fullscreen mode


.cookie-consent {
  background-color: #fff;
  bottom: 0px;
  left: 0px;
  padding: 20px;
  position: fixed;
  right: 0px;
}


Enter fullscreen mode Exit fullscreen mode

If we don't add any specific spacing the link would fall below the safe area and it wouldn't be clickable.

User hasn't scrolled and the link is clickableThe user hasn't scrolled, link is clickable.

User has scrolled and the link is below the safe area and not clickableScrolled, 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 property 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);
}


Enter fullscreen mode Exit fullscreen mode

User hasn't scrolled and the link is clickableThe user hasn't scrolled, link is clickable.

User has scrolled and the link is above the safe area and is clickableScrolled, 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.

Top comments (0)