Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 139 ยท Values and Units

env() and attr(): Reading the Device and the HTML

Use env() to respect notches and safe-area insets with fallbacks, and attr() to pull HTML attribute values into content and, with typed attr(), into real properties.

Most CSS values come from your stylesheet. Two functions reach outside it. env() reads values that the browser or device owns, such as the part of a phone screen hidden behind a notch. attr() reads values from the HTML of the element itself, such as a data-label attribute.

Both are small, but each solves a problem nothing else solves. env() stops your fixed footer from sitting under the iPhone home indicator. attr() lets one rule print every link's URL on paper, label table cells on a phone, or size a progress bar from a data-value attribute. Think of them as relatives of var(): the browser substitutes a value, and you supply a fallback in case it can't.

env(): values owned by the browser

An environment variable is a named value that the user agent provides to the whole document. You read it with env(name) or env(name, fallback). The one you will meet most often is the set of safe-area insets.

Phones have rounded corners, camera cutouts, notches and home indicators. By default the browser keeps your page inside the "safe" rectangle. When you opt in to fill the whole screen, parts of your layout can end up underneath hardware. The four insets tell you how much space to leave:

Variable What it measures
safe-area-inset-top Distance from the top edge to safe content (notch, status bar)
safe-area-inset-right The same for the right edge (landscape notch)
safe-area-inset-bottom The same for the bottom edge (home indicator)
safe-area-inset-left The same for the left edge (landscape notch)

The opt-in is a viewport meta tag. Without viewport-fit=cover browsers keep the page inside the safe area, and the insets are 0:

HTML
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">

With that in place, a fixed bottom bar can protect its buttons:

CSS
.tab-bar {
  position: fixed;
  inset: auto 0 0 0;
  padding: 12px 16px;
  padding-bottom: calc(12px + env(safe-area-inset-bottom));
}

Fallbacks, and what they really do

env(safe-area-inset-bottom, 20px) has a second argument. It is the value used when the browser doesn't know that variable name, for example in an older browser. It is not used just because the inset is zero. On a desktop browser that supports the variable, env(safe-area-inset-bottom, 20px) resolves to 0px, not 20px.

So if you want "at least 12px, more on notched devices", reach for max():

CSS
padding-bottom: max(12px, env(safe-area-inset-bottom));

Normal screens have an inset of 0, so max() picks 12px. On an iPhone with a home indicator the inset is larger, and max() picks that. For the left and right edges the same trick keeps page margins comfortable in landscape:

CSS
.page {
  padding-inline: max(16px, env(safe-area-inset-left), env(safe-area-inset-right));
}

You can't test real insets in a desktop browser, but you can simulate them. The demo wraps the inset in a custom property, so the slider (which stands in for a device) can override it. On a real phone you would leave the slider out and let env() supply the number.

Respecting a safe-area inset

Drag the slider up. The bar's padding follows max(10px, var(--sab)): below 10px nothing changes, above 10px the buttons rise away from the white home-indicator line.

Other environment variables

Safe-area insets are the stable, widely supported set. A few more exist, and each has a narrow purpose:

  • titlebar-area-x, -y, -width, -height describe the draggable title-bar region of an installed web app that uses the Window Controls Overlay feature, so your custom header doesn't sit under the minimize and close buttons.
  • keyboard-inset-top, -height, -bottom and others give the rectangle covered by an on-screen keyboard, once a page opts in through the VirtualKeyboard API. Chat inputs use them to stay visible.
  • viewport-segment-* describe the separate screens of a foldable device.

Unknown names are not an error. They just resolve to their fallback, so always supply one when you use anything beyond the safe-area insets.

env() works like var() when it comes to where it can go: any property value, inside calc(), min(), max() and clamp(). It cannot appear in a media query condition. If you need a layout change at a particular width, use the viewport and media queries as usual.

attr(): reading an attribute

The attr() function replaces itself with the value of an HTML attribute on the element it is applied to. It has worked for many years in one place, the content property of pseudo-elements:

CSS
a[href^="http"]::after { content: " (" attr(href) ")"; }
.tag::before           { content: attr(data-label); }

The result is always plain text. Markup in the attribute is never parsed, so attr() is safe to use with user-supplied values. If the attribute is missing, attr() yields an empty string, or the fallback you give: attr(data-label, "Unknown").

Two uses show up everywhere:

  • Print stylesheets reveal where a link goes (see Print Styles).
  • Responsive tables repeat the column heading in front of each cell once the table turns into stacked cards on a narrow screen. The label lives in HTML, so translators and CMS authors can edit it, and the CSS stays generic.
Stacked table cells labelled with attr()

Typed attr(): attributes as real values

Historically attr() only fed content, which is why it felt limited. The newer typed form can feed any property, as long as you tell the browser what type to interpret the attribute as:

CSS
.bar   { width: attr(data-value type(<percentage>), 0%); }
.swatch { background: attr(data-color type(<color>), #cbd5e1); }
.col   { --span: attr(data-span type(<number>), 1); }

The syntax is attr(name type(<syntax>), fallback). The attribute data-value="72%" becomes the percentage 72%. If the attribute is missing, or its text doesn't parse as that type (for example data-value="lots"), the fallback is used. A bare type(<length>) expects the unit to be written in the attribute (data-w="120px"); to accept a plain number such as data-w="120" and add the unit yourself, read it as a <number> and multiply inside calc().

Typed attr() is new. Chromium-based browsers ship it, while others may not yet, so treat it as progressive enhancement and keep the page meaningful without it. Test for support with @supports:

CSS
@supports (width: attr(x type(<length>))) {
  /* typed attr() rules */
}
Bars sized by data-value

In a browser with typed attr() the three bars have different lengths and colors. The third bar has no data-color, so it takes the teal fallback. In a browser without it, all bars are full width and each still shows its number, so nothing is lost.

Don't hide important content in attributes just so CSS can print it. Text that arrives through content is not selectable, may be skipped or announced inconsistently by assistive technology, and can't be translated by page tools. Use attr() for labels and decorations, and keep real information in the HTML.

env() and attr() side by side

env() attr()
Reads from Browser or device The element's own HTML attributes
Typical use Safe areas, title bar, keyboard Labels, link URLs, data-driven sizes
Fallback is used when The variable name is unknown The attribute is missing or has the wrong type
Works everywhere? Safe-area insets: yes, on current browsers In content: yes. Typed attr(): not yet in all browsers

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. On a desktop browser that supports safe-area insets, what does env(safe-area-inset-bottom, 20px) resolve to?

    The fallback is used only when the variable name is unknown. Here the name is known, and the value is 0.
  2. 2. Which declaration gives a bar at least 12px of bottom padding, and more on devices with a home indicator?

    max() picks the larger of the two values. min() would do the opposite, and a bare + is not valid outside calc().
  3. 3. What must a page do before safe-area insets become non-zero on a notched phone?

    With the default viewport behavior the browser keeps content inside the safe area. viewport-fit=cover lets the page extend under the notch, and then the insets tell you how much to avoid.
  4. 4. What does content: attr(data-label) do when the element has no data-label attribute?

    A missing attribute gives an empty string, unless you provide a fallback as the second argument.
  5. 5. Which rule makes a bar's width come from data-value="60%"?

    Only the typed form of attr() can feed a property other than content: attr(name type(<syntax>), fallback).

Summary

  • env(name, fallback) reads browser-owned values. The fallback applies only when the name is unknown, so a zero inset still resolves to zero.
  • Use max(12px, env(safe-area-inset-bottom)) to keep a minimum spacing and add more on notched devices, and set viewport-fit=cover to make insets non-zero.
  • Other environment variables (titlebar-area-*, keyboard-inset-*, viewport-segment-*) serve installed apps, virtual keyboards and foldables.
  • attr() in content inserts attribute text, which is plain and safe. It is great for print URLs and stacked-table labels.
  • Typed attr(name type(<percentage>), fallback) feeds real properties but is new, so wrap it in @supports and keep a usable default.

Next: The Box Model.