Safe Area Inset Tailwind Helpers

Or how I learned to love the notch…

The Problem

Tailwind is great, sometimes so great you find you can create a whole project without a single line of css.

But then you preview your app on one of the new iOS/Android devices that include a notch!

Example of broken layout with notches

It can look even worse if you’ve done the right thing and added the viewport-fit meta data.

<meta name='viewport' content='initial-scale=1, viewport-fit=cover'>

Example of broken layout with viewport fit cover

The Solution

WebKit in iOS & Android include a CSS function, env(), and a set of four pre-defined environment variables, safe-area-inset-left, safe-area-inset-right, safe-area-inset-top, and safe-area-inset-bottom. When combined, these allow style declarations to reference the current size of the safe area insets on each side.

The Safe area variables

CSS implementation

I created a collection of tailwind like css helper classes to allow apps to reference these safe areas as either margin or padding classes. For example:

.pt-safe {
  padding-top: env(safe-area-inset-top);
}

Check out this gist for the full implementation.

Fixed layout

Tailwind Plugin

I have also recently found a tailwind plugin, tailwindcss-safe-area that will bundle these classes up negating the need for you to polute that lovely clean css file!

Limitations

One limitation to this solution is that you can’t stack the safe-inset value on to an existing padding amount.

In the following example we have a header with a top padding of 8 (2rem). We want to also include the safe inset top area when on a notched device. The following implementation will not work, instead un notched devices will get a top padding of 0px and notched just the safe-area-inset-top amount.

  <header class="pt-8 pt-safe bg-red">
    <h1>My Heading</h1>
  </header>

I would usually resolve this by including a wrapping div to apply the safe-area-inset to.

  <header class="pt-8 bg-red">
    <div class="pt-safe">
      <h1>My Heading</h1>
    </div>
  </header>

There is another tailwind plugin tailwindcss-padding-safe that allows you to use stacked class helpers like pt-8-safe if that’s your preference.

Jim Wardlaw

Developer, Designer, UX Zealot. Ember & Tailwind