Home >Web Front-end >CSS Tutorial >Why Do Scoped CSS Custom Properties Fail to Override Inherited Values?
Scoped CSS Custom Properties: Overriding Inherited Values
When working with CSS custom properties, the scope in which they are defined affects their behavior. In this case, scoped custom properties are being used to scale sizes based on a variable defined in an outer scope. However, the desired effect is not achieved, as all three lists appear at the same scale.
Understanding the Scoping Issue
Custom properties defined with -- that are not nested within other rules are considered globally scoped and affect all elements within the document. However, when a custom property is defined within a nested rule, it becomes scoped to that rule and its descendants. This means that any elements outside of that rule will not inherit the custom property's value.
Resetting the Custom Property
In the provided code, the root element defines the --scale custom property and calculates the --size-* values based on it. Subsequently, child elements define their own --scale custom property. This results in the child elements overriding the inherited --scale value from the root element.
To address this, it is necessary to reset the --scale custom property within the child elements to a new value that will be used for the calculations. By doing so, the custom property is effectively scoped to the child elements and their descendants.
Updated Code
Here is an updated version of the code with the fixes:
:root { --size-1: calc(1 * var(--scale, 1) * 1rem); --size-2: calc(2 * var(--scale, 1) * 1rem); --size-3: calc(3 * var(--scale, 1) * 1rem); } .size-1 { font-size: var(--size-1) } .size-2 { font-size: var(--size-2) } .size-3 { font-size: var(--size-3) } .scale-1x { --scale: 1 } .scale-2x { --scale: 2 } .scale-3x { --scale: 3 } html { font: 1em sans-serif; background: papayawhip; } ol { float: left; list-style: none; margin: 1rem; }
The above is the detailed content of Why Do Scoped CSS Custom Properties Fail to Override Inherited Values?. For more information, please follow other related articles on the PHP Chinese website!