CSS variables are custom properties that are defined in one place and used in multiple places throughout the stylesheet.
CSS variables are used in two principle steps:
Define the custom variable inside a selected elementLoading...
var()function to allow
--custom-variableto be assigned to a property in multiple elements:Loading...
CSS Variables and the Cascade
CSS cascade rules makes custom variable properties inheritable. This means that any child or grandchild element can inherit that variable value.
In the samples below, there are 3
div elements with classes
divC. The hierarchy is as follows:
divAis the topmost parent in the body
divBis a child of
divCis a child of
divB(and a grand-child of
The CSS variable
--custom-bg-color-saffron is defined in the selector for
The rendered image below shows that the background color for
divB is set to
--custom-bg-color-saffron. While its child,
divC, doesn’t have background color specified, it inherits the property from its parent. On the other hand,
divA, the parent of
divB, has a default white background color because it exists outside the scope of