Properties Worthy of Mention
Here are some behaviors that are worth mentioning.
1. Custom properties are ordinary properties, so they can be declared on any element.
Declare them on a paragraph element, section, aside, root, or even pseudo-elements. They’ll work as expected.
2. CSS variables are resolved with the normal inheritance and cascade rules
Consider the block of code below:
div {
--color: red;
}
div.test {
color: var(--color)
}
div.ew {
color: var(--color)
}
As with normal variables, the --color
value will be inherited by the divs
3. CSS variables can be made conditional with @media
and other conditional rules
As with other properties, you can change the value of a css variable within a @media
block or other conditional rules.
For example, the following code changes the value of the variable, gutter on larger devices.
:root {
--gutter: 10px
}
@media screen and (min-width: 768px) {
--gutter: 30px
}
4. CSS variables can be used in HTML’s style attribute.
You can choose to set the value of your variables inline, and they’ll still work as expected.
<!--HTML-->
<html style="--color: red">
<!--CSS-->
body {
color: var(--color)
}
CSS variables are case sensitive. Be careful with this one. I save myself the stress and write variables in the lower case. Your mileage may vary.
/*these are two different variables*/
:root {
--color: blue;
--COLOR: red;
}
Get hands-on with 1200+ tech skills courses.