iPhone X layout features with CSS Environment variables

Dragan Eror
Mar 22, 2018 · 2 min read

Recently I had a task to implement new layout features to iPhone X by using its features from iOS 11 and WebKit.

To enable those features use viewport-fit=cover in the viewport meta tag.

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

Now, if device is capable of understanding that, it will use full display layout for the content area (safe area).

Then, you can use constant() for iOS 11.0–11.2 and env() for iOS versions higher than 11.2.

Example

padding-top: env(safe-area-inset-top);

CSS Environment predefined variable names are:

  • safe-area-inset-top
  • safe-area-inset-right
  • safe-area-inset-bottom
  • safe-area-inset-left

You can use them inside constant() or in env() functions.

You will find in many sources on the internet that env() will work anywhere var() works, but that is not the case. From experience, sometimes it will not work inside calc(). In that case, use Custom CSS Properties (CSS native variables).

Example

// This WILL NOT work.
.selector {
height: calc(100% + (env(safe-area-inset-top) + env(safe-area-inset-bottom)));
}
// This WILL work.
.selector {
--safe-area-inset-top: env(safe-area-inset-top);
--safe-area-inset-bottom: env(safe-area-inset-bottom);
height: calc(100% + (var(--safe-area-inset-top) + var(--safe-area-inset-bottom)));
}

Using env() on older devices can produce some BUGs, because older browsers do not know how to understand env(). To support older devices, you can use fallback property values.

Example

// Older browsers (do now support CSS Environment variables).
.selector {
height: 100%;
}
// Browsers which partially support CSS Environment variables (iOS 11.0-11.2).
@supports (padding-top: constant(safe-area-inset-top)) {
.selector {
--safe-area-inset-top: constant(safe-area-inset-top);
height: calc(100% + var(--safe-area-inset-top));
}
}
// Browsers which fully support CSS Environment variables (iOS 11.2+).
@supports (padding-top: env(safe-area-inset-top)) {
.selector {
--safe-area-inset-top: env(safe-area-inset-top);
height: calc(100% + var(--safe-area-inset-top));
}
}

Dragan Eror

Written by

Drupal and Front End developer, Open Source enthusiast! Enjoy in motorcycles. Like to do things right not quick.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade