In CSS, we often encounter the need to manipulate properties based on the inherited value, such as inheriting the background color of an element for its pseudo-elements. However, using the inherit keyword in a CSS variable doesn't always work as expected.
Consider this simplified example:
:root { --color: rgba(20, 20, 20, 0.5); /* Default value */ } .box { /* Properties... */ } .box:before { background: var(--color); /* Other properties... */ }
In this scenario, we add a pseudo-element (::before) to the .box element and set its background property to use the --color CSS variable. However, if we want the pseudo-element to inherit the background color of .box using the inherit keyword, it won't work as expected.
To store an inherited value in a CSS variable, we can use the property's fallback value. The fallback value is specified as the second argument to the var() function. For instance:
background: var(--color, inherit);
By doing this, we tell the background property to use inherit as a fallback value if the --color variable is not defined.
However, in our case, this won't work because --color is always defined at the :root level. To overcome this issue, we can use the initial value to undefined our custom property and force the use of the fallback value:
.box:before { background: var(--color, inherit); /* Other properties... */ } /* Undefine --color using the initial value */ .box:before { --color: initial; }
The initial value sets the CSS variable to its initial value, which is an empty value. When a CSS variable has an initial value, var() treats it as having its fallback value.
By using this approach, we can store the inherited value in the --color CSS variable and use it effectively for the background property of the pseudo-element.
The above is the detailed content of How Do You Store Inherited Values in CSS Variables?. For more information, please follow other related articles on the PHP Chinese website!