I have a component that supports theming by exposing SASS variables and I'm trying to convert these variables to native CSS variables. In the example below, I expose the color variable for consumers to optionally be able to set it. If they don't set it, the property just gets totally ignored, as if it was never set.
// button.scss
$color: null !default;
button {
color: $color;
}
I thought the conversion to a CSS variable below would be equivalent:
button {
color: var(--color);
}
I haven't defined the variable, so it's considered invalid. As stated in What happens with invalid variables? though:
When the browser encounters an invalid var() substitution, the initial or inherited value of the property is used.
This means that when either the initial or inherit value is used, any consumer's default styles will be overridden. Let's assume that our button component exposes a few variables, but consumers decide to set only the color variable, leaving the rest untouched (either to browser's default or to another library's global styles):
/* bootstrap.css (optionally) */
button {
border: 2px solid blue;
}
/* button.css */
button {
color: var(--color);
background-color: var(--background-color);
border: var(--border);
}
/* page.css */
button {
--color: red
}
<button>No border or browser's background color</button>
I would expect the button to have a red text color, a light grey background color (from the browser) and a 2px solid blue border, but instead the background color and border have disappeared entirely.
Is there any way to achieve the SASS equivalent or do CSS variables just come with this culprit? If it's the latter, I'm really surprised by this implementation and I'm curious why more people not bringing this up, especially since the !default and null from SASS are so useful and widespread.