Adds fallbacks to your CSS var() functions
npm install postcss-custom-properties-fallbackThis plugins adds fallbacks to your [CSS Custom Properties] and works well as a compantion to [PostCSS Custom Properties].
If we remove --color from :root, what color will h1 have in modern browsers?
``diff
:root {
- --color: red;
}
body {
color: green;
}
h1 {
color: red;
color: var(--color);
}
`
h1 is red
!The text "Wrong answer!" over a cat screaming while firing an automatic rifle
Nope, it's green!
Intuitively it's easy to think that if --color isn't defined, then the browser should skip the color: var(--color) and use the valid color: red above it.
Especially since this is what happens in older browsers that don't support [CSS Custom Properties].
The right answer is to use the second argument in var() (see Example 10 in the spec), also known as the fallback argument:
`css`
color: var(--color, red);
Now it works like expected. See the spec for more information on how invalid/missing values are treated.
h1 is green
!The text "Yes!" over a smiling and nodding Jack Nicholson
Right answer! Check the wrong answer to learn why that is.
Add [PostCSS Custom Properties Fallback] to your project:
`bash`
npm install postcss-custom-properties-fallback --save-dev
Use it as a [PostCSS] plugin:
`js
const postcss = require('postcss');
const postcssCustomPropertiesFallback = require('postcss-custom-properties-fallback');
postcss([postcssCustomPropertiesFallback(/ pluginOptions /)]).process(
YOUR_CSS /, processOptions /
);
`
The importFrom option is required. It works like from [CSS Custom Properties], except it doesn't support importing from CSS yet.
`js`
postcssCustomPropertiesFallback({
importFrom: { customProperties: { '--color': 'red' } },
});
`pcss
h1 {
color: var(--color);
}
/ becomes /
h1 {
color: var(--color, red);
}
``
[css custom properties]: https://www.w3.org/TR/css-variables-1/
[postcss]: https://github.com/postcss/postcss
[postcss custom properties]: https://github.com/postcss/postcss-custom-properties
[postcss custom properties fallback]: https://github.com/stipsan/postcss-custom-properties-fallback