CSS variables

In the modern1 web things aren’t fixed as they were a few years ago. Responsive design is now a standard that directly impacts not just how your users experience your website but also ranking in search engines.

Website performance is more so important especially now that being able to build things isn’t enough if those things don’t perform well and the distinction between application and website is getting more a more blurred. Exciting new features are available now on this robust platform making working with the web easier, less-hacky and fun

Cascading Style Sheets (CSS) has mostly been on the backseat when it comes to “languages” on the web (atleast HTML has language in it’s name) but this has been changing with the things we are now able to do with CSS. We had come up with ways to make CSS more robust but most of those ways have been non-native and require extra setup on build; Sass and LESS will have limitations when it comes to changes needed on runtime. In early 2018, the W3C put out a draft for the cascading variables module which allows for reusable variables in CSS.

Usage

As of the current date of writing this post; support for CSS variables is available on most2 browsers.

To declare a variable the syntax is --[variable-name]: [value]; and can then be used in a cascading fashion in place of values.

Example
:root {
  --global-padding: 2rem;
}

header {
  padding: var(--global-padding);
}

Default values

Cascading variables supports a default fallback value which will be applied if the variable specified is invalid.

header {
  --spacing: 2rem;
  background: var(--spacing, yellow);
}

yellow will be applied since 2rem is not a valid color

Common Gotchas

As of writing this post, there’s a few things that aren’t (yet) possible with CSS variables.

  • Can’t be used in media queries. So @media(var(--breakpoint)){ ... } won’t work
  • Concatenation without calc. padding: var(--space-unit)px; won’t work instead padding: calc(var(--space-unit) * 1px); works

Depending on your project and users of your product, it’s definitely worth considering using CSS variables. I’d like to know your experiences and use cases for CSS variables.


  • 1Modern, to the time of writing this post
  • 2Unfortunately Internet Explorer doesn't have good support...yet