- With npm:
npm install css-vars
- With yarn:
yarn add css-vars
- With Bower:
bower install css-var
- Manually: get this file
Include the main mixin file in your project using an
To declare variables, use
@include css-vars(<map of variables>)
(you can reuse Sass variables):
// $css-vars-use-native: true;;;;
To use variables, use the
The default output from the above is:
$css-vars-use-native: true; is uncommented, native CSS Custom Properties are used:
Declaration in selectors, reassigning variables
Variables are declared on the global scope (
$css-vars map for Sass,
root for native CSS).
You can declare variables inside selectors and, of course, redefine any variable, e.g.:
// declaration outside of any selectors));header
var() function takes the second param to assign the default value if a variable is not defined:
Advantages of the mixin
Usage of the mixin gives the useful debug information:
- logs when a variable was not assigned but used
- logs when some variable is reassigned
- provides info when a variable is not defined, but there is a default value passed, which is used instead
This information is helpful in both cases for Sass and CSS variables.
None browsers so far provide such debug info for CSS custom properties.
To enable the mixin debug messages output during the Sass compilation, just add the following to your project:
Trigger using of native CSS Custom Properties
To switch the mixin to use native CSS Custom Properties, just provide:
It's useful when:
- You don't support browsers without CSS Custom Properties
- To generate a separate CSS file which will be used for browsers which support them
const isSupported = windowCSS && windowCSSsupports &&windowCSS;if!isSupported;;
There are some caveats, when CSS Custom Properties work in a different way.
E.g. they cannot be used inside Media Query values, so the following code will work in Sass, but not in CSS (when you switch):
Another differences are regarding the different scopes for CSS and Sass variables.
E.g. when you use assigned variable to define something in CSS and then reassign it- the used value will be updated. sass just inline values, so there will be no effect when you change a variable after.
To debug such cases when you switch just enable the debug messages:
Limitations (in case of Sass variables)
There are some limitation because of the Sass nature:
mixin uses the global map to reassign variables, which may result in a different behavior from Custom Properties when non global variables are used.
Before passing a map of variables to the mixin, Sass invokes all the functions in it, together with var(). As result you cannot reuse variables in one declaration, e.g. this will not work:
To make it work, just split the declaration and the usage:
- Sass doesn't invoke functions inside
calc(), so in that case you have to trigger that using Sass interpolation