Read more

CSS variables aka CSS Custom Properties

Dominik Schöler
September 11, 2020Software engineer at makandra GmbH

CSS variables are very different from preprocessor variables. While preprocessors use variables to compile a static piece of CSS, CSS custom properties are a reactive (i.e. live) part of the styles. Think of them like usual CSS properties that cascade, but have:

  • a special syntax: CSS variables always start with a double-dash (--color)
  • no inherent meaning: Defining a CSS variable will not change any styles in itself
  • a special functionality: CSS variables can be used within the values of other properties, including CSS variables (var(--color))
  • a superpower: they can be used to influence the Shadow DOM of Web Components Show archive.org snapshot
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

CSS variables are a means to store CSS values with elements and have them cascade according to the DOM structure instead being based on the CSS structure (as it is in preprocessors). This open up a whole new set of possibilities, especially for adapting components. E.g. button styles could be changed by simply setting a variable, with no need to even know what CSS properties use that value.

They're supported by all modern browsers Show archive.org snapshot .

Quick example

body {
  --shadow-color: gray;
}

button {
  box-shadow: .1em .1em .1em var(--shadow-color);
}

button:hover {
  --shadow-color: skyblue;
}

Resources

Posted by Dominik Schöler to makandra dev (2020-09-11 11:40)