Search⌘ K

Common Mistakes and Gotchas

Explore how CSS variables work, common pitfalls like multiple declarations and cyclic dependencies, and understand how invalid values affect styling. This lesson helps you master troubleshooting and best practices when working with CSS custom properties.

Resolving Multiple Declarations

As with other properties, multiple declarations are resolved with the standard cascade.

Let’s see an example


/*define the variables*/
:root { 
	--color: blue;
 }
 
div { 
 	--color: green; 
}
  
#alert { 
 	--color: red; 
}
 
/*use the variable on all elements*/
* { 
	color: var(--color); 
}

With the variable declarations above, what will be the color of the following elements?

<p>What is my color? </p>
 <div>and me? </div>
 <div id='alert'>
   What is my color too?
   <p>color? </p>
 </div>

Can you figure it out?

The Solution

The first paragraph will be blue. There is no direct --color definition set on a p selector, so it inherits the value from :root

:root { --color: blue; }

The first div will be green . That’s kind of obvious. ...