It is true, the CSS variable feature may break in legacy browsers. But fear not, there is a solution! You can utilize the postcss-css-variables
plugin to handle the conversion for you. This way, you can continue to use CSS variables without worrying about compatibility issues with older browsers. Once those legacy browsers are no longer relevant, simply remove the plugin.
For more information, check out the details at https://www.npmjs.com/package/postcss-css-variables.
There is even a playground available where you can experiment and see how it works firsthand.
For instance,
:root {
--color-background: #ffaaaa;
--font-color: #2222ff;
}
@media (prefers-color-scheme: dark) {
:root {
--color-background: #aaaaff;
--font-color: #ffFF22;
}
}
body {
background-color: var(--color-background);
}
p {
color: var(--font-color);
}
will be transformed into
body {
background-color: #ffaaaa;
}
@media (prefers-color-scheme: dark) {
body {
background-color: #aaaaff;
}
}
p {
color: #2222ff;
}
@media (prefers-color-scheme: dark) {
p {
color: #ffFF22;
}
}