agronskiy
agronskiy

Reputation: 367

Using rem to set font-size inside :root element works. Why?

I recently ran into the fact that the following code works like a charm:

:root {
  font-size: .8rem;
}

(i.e. it rescales the default size).

My question is: why does this work? Am I right that using rem inside :root should be illegal or ill defined (for the very reason that rem is defined as relative to :root's font-size itself — so using rem for defining :root's properties is at least weird).

Thanks!

P.S. This is kind of 'meta question' fro understanding the computation mechanics behind CSS. I am pretty much sure that the canonical way to do this is set percentage size on root element (a.k.a. <html>).

Upvotes: 4

Views: 3507

Answers (1)

Danny
Danny

Reputation: 1113

rem values are relative to the root element's font-size property which for HTML documents is the html element.

As per the CSS Values and Units Module Level 3 about rem values:

Equal to the computed value of font-size on the root element. When specified on the font-size property of the root element, the rem units refer to the property’s initial value

If there is no explicit value set on the root element it inherits it's value from the browser settings that the user can change; normally the default font size in the browser settings is 16px or medium.

So if you set rem on the root element you're setting it relative to the default value from the browser settings

Upvotes: 6

Related Questions