Can I assign one globally defined CSS variable to another locally define variable?
For example, the variable --dark
has been globally defined as black
.
Then, I want to be able to do:
:root {
--background-color: --dark
}
.light {
--background-color: white
}
div {
background-color: --background-color
}
So that by default, my div
will have a black background. And when the class light
is added to it, it will have a white background.
I need the 'default' --dark
variable here because it is a theme variable.
CSS variables have access to the DOM, which means that you can create variables with local or global scope, change the variables with JavaScript, and change the variables based on media queries. A good way to use CSS variables is when it comes to the colors of your design.
To declare a variable in CSS, come up with a name for the variable, then append two hyphens (–) as the prefix. The element here refers to any valid HTML element that has access to this CSS file. The variable name is bg-color , and two hyphens are appended.
CSS variables have access to the DOM, which means that you can change them with JavaScript.
The @property “at-rule” in CSS allows you to declare the type of a custom property, as well its as initial value and whether it inherits or not.
With native CSS variables, things are a little different. You reference a variable by using the var () function. With the example above, using CSS Variables will yield this: :root { --font-size: 20px}.test { font-size: var (--font-size)}
The var() Function. Variables in CSS should be declared within a CSS selector that defines its scope. For a global scope you can use either the :root or the body selector. The variable name must begin with two dashes (--) and is case sensitive! The syntax of the var() function is as follows: var(custom-name, value)
But sadly, CSS has lacked support for native variables from the very beginning. You write CSS? Then no variables for you. Well, except if you were using a preprocessor like Sass. Preprocessors like Sass sell the use of variables as a big add-on.
The initialization of the CSS variable is done by prefixing “–” to the variable name. For example, the following syntax initializes the variable “my_font” to 20px. The “my_font” variable can now be used anywhere inside the code with a value of “20px”. Next comes the substitution part.
You should assign as var(--dark)
:root {
--dark : black;
--background-color: var(--dark);
}
.light {
--background-color: white;
}
div {
height: 100px;
width: 100px;
background-color: var(--background-color);
}
<div class="light"></div>
<div></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With