CSS Custom Properties

what are they?

The ability to define variables in CSS and then use those variables in multiple places

Native CSS Variables === CSS Custom Properties

problem

  • applications can contain lots of CSS
  • many of the css values are duplicate
  • changing the values is tedious & error prone
  • understanding the structure and relationships is hard
:root {
  --primary-color: white;
  --secondary-color: black;
}
:root {
  --primary-color: white;
  --secondary-color: black;
}

article {
  color: var(--secondary-color);
  background-color: var(--primary-color);
}

define 'em

  • must be inside an element
  • starts with two dashes
  • followed by an accurate and descriptive name
  • case sensitive
  • works with 'shorthand properties'
<selector> {
  --<descriptive-name>: <value>;
}

they cascade!

use 'em

with the var() function

var(--<variable name> [, <default value> ])

var() uses

  • as any part of a value in any property
  • can be used with calc()

invalid var() uses

  • as property names,
  • selectors,
  • query part of media query
  • nor anything else

will revert to initial

  • invalid values
  • circular references

why use preprocessor variables

?

1. browser support

why use native CSS custom properties

?

  1. don't need a preprocessor
  2. they cascade!
  3. browser repaints when values change
  4. can be modified from JavaScript at runtime!

browser support

  • all but i.e. and edge
  • edge is currently being developed

what if

?

postcss-css-variables

  • postcss plugin
  • with the preserve option it...
    • leaves css custom properties in your code
    • adds static values for dumb browsers

postcss-css-variables

:root {
  --color: red;
}

div {

  color: var(--color);
}
:root {
  --color: red;
}

div {
  color: red;
  color: var(--color);
}

before

after

css custom properies = now!

react stack support

  • currently substituting at build time
  • adding postcss-css-variables soon*

cascade example

Credits

native support makes it

dynamic!

CSS Custom Properties

By Bruce Campbell

CSS Custom Properties

  • 972