CSS for Web Development

0% completed

Previous
Next
CSS env() Function

The CSS env() function lets you access special environment variables provided by the device. This is especially useful on devices with notches or rounded corners. For instance, you can adjust padding or margins so that content does not overlap with areas reserved by the device.

The env() function is mostly used to work with safe areas, like safe-area-inset-top, safe-area-inset-right, safe-area-inset-bottom, and safe-area-inset-left.

Syntax

property: env(variable-name);

Explanation:

  • env(variable-name):
    • Retrieves the value of the environment variable (for example, safe-area-inset-top).
    • You can use this function to adjust layout spacing based on the device's safe area insets.

Example 1: Adding Safe-Area Padding to a Header

In this example, the header has padding that adjusts for the top safe area on devices with notches.

HTML

. . . .

Explanation:

  • Padding Calculation:
    • The header's padding is computed as 10px plus the top safe area inset.
  • Outcome:
    • On devices with a notch, the header will have more top padding to ensure that the content is not cut off.

Example 2: Adjusting Bottom Padding for a Full-Screen Element

In this example, a full-screen container uses the safe area inset at the bottom to ensure that its content stays clear of any display cutouts.

HTML

. . . .

Explanation:

  • Full-Screen Container:
    • The container takes up the full viewport using 100vw and 100vh.
  • Dynamic Padding:
    • The bottom padding is calculated as 20px plus the safe area inset at the bottom.
  • Outcome:
    • This ensures that on devices with a bottom inset, such as iPhones with a home indicator, the content stays visible and properly spaced.

By using the env() function, you can build layouts that adapt to the special conditions of modern devices, ensuring that your content is always accessible and well-spaced.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next