CSS Environment Variables

0
50

We were all introduced to the env() function in CSS when all that drama about “The Notch” and the iPhone X was going down. The way that Apple landed on helping us move content away from those “unsafe” areas was to provide us essentially hard-coded variables to use:

padding:
env(safe-area-inset-top)
env(safe-area-inset-right)
env(safe-area-inset-bottom)
env(safe-area-inset-left);

Uh ok! Weird! Now, nine months later, an “Unofficial Proposal Draft” for env() has landed. This is how specs work, as I understand it. Sometimes browser vendors push forward with stuff they need, and then it’s standardized. It’s not always waiting around for standards bodies to invent things and then browser vendors implementing those things.

Are environment variables something to get excited about? Heck yeah! In a sense, they are like a more-limited version of CSS Custom Properties, but that means they can be potentially used for more things.

CSS environment variables are getting standardized:https://t.co/QKFBM3WFT2
Allow to get and use the browser- and author-defined variables: typography, colors, notch and other specific layout/device values.
They work in Media Queries, where CSS Custom Properties cannot be used. pic..com/FWrPiBiAqp

— Serg Hospodarets (@malyw) April 29, 2018

👀 Brand new spec for global env() variables in CSS: https://t.co/6YfXWFTyhN

Forget notches, the important thing here is the ability to separate CSS variables from the cascade. Cool ① for perf/code organization ② because you might be able to use them in media queries!

— Eric Portis (@etportis) April 30, 2018

Eric also points out some very awesome early thinking:

ISSUE 4 – Define the full set of places env() can be used.

  • Should be able to replace any subset of MQ syntax, for example.
  • Should be able to replace selectors, maybe?
  • Should it work on a rule level, so you can insert arbitrary stuff into a rule, like reusing a block of declarations?

Probably still changeable-with-JavaScript as well. I would think the main reason CSS Custom Properties don’t work with media queries and selectors and such is because they do work with the cascade, which opens up some very strange infinite loop logic where it makes sense CSS doesn’t want to tread.

If you’re into the PostCSS thing, there is a plugin! But I’d warn… the same issues that befall preprocessing CSS Custom Properties applies here (except the first one in that article).