Scoped Custom Property Inheritance in CSS
When defining custom properties in CSS, scoping plays a crucial role in their inheritance and usage. However, you may encounter situations where a scoped custom property is ignored when used to calculate a variable in an outer scope. This can occur when a custom property is redefined within a child element, leading to unexpected results.
Explanation of Scoping
Custom properties are defined using the -- prefix and can be scoped to a specific element or subtree using the :root or :host keywords. Scoped properties are only accessible within the element or its descendants, allowing for encapsulation and controlled inheritance.
Issue with Scoped Properties and Calculations
In your example, you have defined the scoped custom property --scale in the :root selector to calculate the values of --size-1, --size-2, and --size-3. However, inside the child elements (.scale-1x, .scale-2x, and .scale-3x), you have redefined --scale. This creates an issue because CSS evaluates custom properties in a top-to-bottom manner. Once a custom property is evaluated at a certain level, it cannot be overridden or altered in nested elements.
CSS Custom Property Technique for Composable Scaling
To achieve the desired effect of scaling lists at different levels without coupling, you can use the following technique:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
In this approach, the --scale property remains scoped to the :root level. However, instead of using it directly to calculate the font sizes, we use it within the var() function inside the .size-1, .size-2, and .size-3 classes. This allows the font size to inherit the value of --scale if it is set in an outer scope. If --scale is not provided, it falls back to a default value of 1rem.
With this technique, you can compose scaling effects without coupling the elements. You can apply the .scale-1x, .scale-2x, and .scale-3x classes to different list elements or groups to achieve the desired scale variation.
The above is the detailed content of Why Do Scoped CSS Custom Properties Sometimes Fail to Cascade Correctly for Calculations?. For more information, please follow other related articles on the PHP Chinese website!