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
?
- don't need a preprocessor
- they cascade!
- browser repaints when values change
- 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
-
CSS Custom Properties for Cascading Variables
https://drafts.csswg.org/css-variables/ - CSS-Tricks: What is the difference between CSS variables and preprocessor variables?
https://css-tricks.com/difference-between-types-of-css-variables/ - My playground codepen
http://codepen.io/eatrocks/pen/RoJyOZ?editors=0100 - Google Chrome Demo
https://googlechrome.github.io/samples/css-custom-properties - Can I use?
http://caniuse.com/#feat=css-variables - postcss-css-variables postcss plugin
https://www.npmjs.com/package/postcss-css-variables -
postcss-css-variables postcss plugin playground
https://madlittlemods.github.io/postcss-css-variables/playground/
native support makes it
dynamic!
CSS Custom Properties
By Bruce Campbell
CSS Custom Properties
- 983