问题
Does global variables in CSS are less efficient in terms of memory or in terms of efficiency as local CSS variables?
so basically my question is whether there's any benefit of having variable which is declared in the the global scope and can be accessed anywhere in the CSS opposed to variables which are declared within the code block of a particular selector and scoped locally in respect to the selector.
when talking about global scope i mean:
:root { --mainColor: red }
and local scope means:
.element { --mainColor: red; }
.element p { color: var(--mainColor) }
hope i'm clear enough :)
回答1:
I disagree with such definition and the use of local and global variable because CSS is not a programming language and it's all about Cascading.
You said:
and local scope means:
.element { --mainColor: red; }
.element p { color: var(--mainColor) }
Based on what you can say thay this is a local scope? you have no idea where the class will be used. If we add such class to the html
element then all the elements will access/inherit the custom property and we can say that the custom property is available globally within the DOM. It will be exactly the same as defining the property within :root
.
Custom properties are ordinary properties, so they can be declared on any element, are resolved with the normal inheritance and cascade rules ref so I don't think that performance will change based on where you declare the property. The perfermance will depend on the HTML used with your CSS. A CSS definition has no meaning without a DOM where it's applied.
来源:https://stackoverflow.com/questions/53694900/global-css-variables-vs-local-variables-in-terms-of-efficiency