iPhone X layout features with CSS Environment variables

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));
}
}

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store