iPhone X layout features with CSS Environment variables

Dragan Eror
2 min readMar 22, 2018

--

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

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