Home > database >  What's the difference between :root and *?
What's the difference between :root and *?

Time:01-24

When we declare variable in CSS, why we do write:

:root
{
    --bgcolor:orange;
}

/* instead of */

*
{
    --bgcolor:orange;
}

What is the difference between both of those things?

CodePudding user response:

:root is a pseudo selector that is equivalent to html 99% of the time, but with higher specificity (specificity equal to html class).

:root selects the root element of the document based on it's format. It exists as CSS can be used in other document formats (SVG, XML).

* would apply the css to every element on the page. This is usually reserved for normalisation, fonts etc.

CodePudding user response:

This is because :root is simply a psuedo selector for the <html> element. When setting CSS custom properties/vars, they are being set on the root element - think of it like a global variable.

If you use * (universal selector) - it's setting the custom property/var on EVERY element (e.g., div, p, span, ect.) in the DOM.

Using :root is simply allowing all children elements access to that property/var without the unnecessary overhead of computing that for all elements of a DOM.

  • Related