Adding to the points made previously, there may arise situations where avoiding declaration of variables in the global :root
scope is preferred. This can be especially useful when creating a reusable component that requires its own locally scoped styles, independent of the overarching project styles - particularly if the component is intended for use by other developers.
In such cases, one approach is to expose a single variable name to the wider development environment, while utilizing a different variable name within the component itself. The container for the component simply links the optional external variable to the internal variable and sets its default value:
.my-component-container {
/* Link optional "external" variables to required "internal" variables */
--my-variable-inner: var(--my-variable, blue);
}
.my-component-container .my-nested-element {
color: var(--my-variable-inner);
}
.my-component-container .my-other-nested-element {
border-color: var(--my-variable-inner);
}
This method ensures that --my-variable-inner
is consistently defined within the component, while allowing external users the flexibility to define --my-variable
as needed.
The trade-off here is managing two variable names instead of one. To streamline this process, consider implementing a project-wide convention, such as appending --inner
or another uniform suffix to each relevant variable.