Cascading CSS variables root confusion

I was a bit confused after i got into this section…

when do we use root?

why do we need to write penguin-belly: pink on root and not just write it on .penguin? Or is the point of this to show that all the classes under :root that is using that particular css variable will be affected?

You want variables all at the very top level so that you can use them anywhere, not for one specific thing (because then there’s no point using a variable)

1 Like

thanks, so all variables should be on root and not on random classes and id’s? did i understand it correctly? because on this specific topic, variables are created on the root and a specific class

thanks, so all variables should be on root and not on random classes and id’s? did i understand it correctly? because on this specific topic, variables are created on the root and a specific class

They’re done that way to show how you can override them: in general they go on root, and then you may end overriding further down the tree (which is what the example shows). The example is simplified though: what I meant is that generally you wouldn’t override right at the bottom.

EDIT: @strivingforthebetter so if you have something like this, and you’ve got some variables for [say] colours:

  • Generally, you would always want the variables defined on :root: that way they’re available everywhere below root on that tree.
  • If you overrode on body, it would still affect everything.
  • If you overrode specifically on the top level header or main, it would overide for that branch of the tree.
  • If you overrode for headers in general, it would affect eavery header in the tree.
  • If you overrode for one of the leaf nodes right at the bottom, the override becomes less useful - for example if you overrode for the first li item in the ul in the main header nav (at the very bottom left of the tree), then that might be pointless: it’s only going to affect one thing, so might as well just write color: #someDifferentColour rather than overriding a variable.