How Do You Store Inherited Values in CSS Variables?

Barbara Streisand
Release: 2024-11-17 05:47:03
Original
799 people have browsed it

How Do You Store Inherited Values in CSS Variables?

Storing Inherit Value in CSS Variables

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.

The Problem

Consider this simplified example:

:root {
  --color: rgba(20, 20, 20, 0.5); /* Default value */
}

.box {
  /* Properties... */
}

.box:before {
  background: var(--color);
  /* Other properties... */
}
Copy after login

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.

The Solution

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);
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template