Coding Cable
Coding Cable

Reputation: 103

:root, html, * selector. Any differences?

Is there any difference between those three CSS rules ?

* {
  font-size: 24px
}
:root {
  font-size: 24px
}
html {
  font-size: 24px
}

Upvotes: 9

Views: 6705

Answers (3)

Ankita Sinha
Ankita Sinha

Reputation: 109

If we have something like this, with all of *, :root and html together as below

* {
  background: green;
}

:root {
  background: yellow;
}

html {
  background: black;
}

h1 {
  background: blue;
}
<h1>This is a heading<span>Cow</span></h1>

The specificity is as below :root(yellow) >html(black)>*(green)

Upvotes: -1

Temani Afif
Temani Afif

Reputation: 272647

Yes there is a difference. Below some examples where the result isn't the same

Using *

* {
  font-size: 24px
}

p {
  font-size:2em;
}
<div>
  <p>some text <span>here</span></p>
</div>

Using html (or :root)

html {
  font-size: 24px
}

p {
  font-size:2em;
}
<div>
  <p>some text <span>here</span></p>
</div>

Applying font-size to all the elements is different from applying the font-size to the html element and having all the elements inherit the value.

In the first example, span will have a font-size equal to 24px because it was selected by *. In the second example, span will inherit the computed value of p since no selector is targetting it.


between html and :root there is a specificity war where :root will be the winner:

html {
  font-size: 999px;
}

:root {
  font-size:24px;
}
<div>
  <p>some text <span>here</span></p>
</div>

:root {
  font-size:24px;
}

html {
  font-size: 999px;
}
<div>
  <p>some text <span>here</span></p>
</div>

Upvotes: 20

user13060720
user13060720

Reputation:

All of them will affect your whole HTML. You can even use a forth option, that would be html * { }, that would work on all of your HTML.

Their meaning are:

  • The * means that will select all elements - as per CSS * Selector.
  • The :root CSS pseudo-class matches the root element of a tree representing the document. In HTML, :root represents the <html> element and is identical to the selector html, except that its specificity is higher.

You can get more example and information on this post from the Community: How to Apply global font to whole HTML document.

Hope this helps!

Upvotes: 3

Related Questions