Confusion with CSS variables

Hello,

I have seen tutorials where many CSS variables are declared in the root element. This obviously ‘makes’ then apply to everything, so is the assumption always that they are just applied to everything and then overwritten further along in the code to the desirec colour?

“Apply to everything” is not the right words here.
The reason CSS variables are declared in the root element is so they are available in the global scope, which means you can call those variables everywhere in your CSS file.

The purpose of CSS variables is, for example, instead of remember the hexcode #6e6a69 for the gray color (which is hard to remember), you can just declared it: --gray: #6e6a69; and call var(--gray) everytime you need to re-use that color.
And if you changed your mind and want a different shade of gray, you just need to change it at one place, which is the variable declaration.

While technically, you can re-declared variables to override their values, it will make your code hard to manage and kind of defeat said purpose above.

So re-declare CSS variables is a bad practice you shouldn’t use.

1 Like

It really depends on the variable, for a color it doesn’t make sense, if it is named gray it should be gray. However, variables can be more generic and context-sensitive. So you’re changing the variable value for the context it is used in.

Changing a variable is really not that different from what you are doing in CSS already. You set a property with an initial/default value and change it depending on its context. At least with the variable, the value has a name. But it does have to be a generic name, so no values in the name (unit, or other fixed values like colors).

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.