Basic CSS: Cascading CSS variables - :root selector

Hi Everyone,

My question is what is the difference between creating a CSS variable in :root selector and creating a CSS variable in .penguin selector?

The variables which are created in .penguin selector cannot be used in other selectors?

Can anyone help me to understand, please?

It can be used throughout even if it’s not declared in :root.

Q: Should I always use the :root pseudo-class as a selector to define variables?

A: Not necessarily, but usually, as doing so serves a couple of purposes. First, it collects all your variables in one place for easy maintenance (especially if that’s the first rule in your CSS file), which is kind of the point. Second, :root matches the whole page (essentially everything in the <html> element), so it makes all your variables global in scope.

1 Like


First of all, thank you replying. And second, the Medium post is very much interesting and useful. My doubts are cleared.

Thank you very much!