3

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>).

4
  • rem is a relative measurement which is best referencing an absolute measurement like 16px.
    – zer00ne
    Apr 23, 2018 at 22:41
  • No. By definition, it is referencing the font size of root. The fact that root's font size is 16 is a coincedence for rem.
    – agronskiy
    Apr 23, 2018 at 22:56
  • "...which is best referencing an absolute measurement like 16px. " Best implies an opinion. like 16px is an example. It isn't a coincidence, most browsers set default font-size of root to be 16px. When setting root font-size to .5em, that's .5 of the root's font-size which is 16px. If you changed the root font-size to 8px it's the same as .5em. It's just better to use an absolute measurement less work.
    – zer00ne
    Apr 23, 2018 at 23:31
  • Thanks, now I see what you mean. But my confusion came exactly from weirdness of setting root font size in units which are defined through the same root font size. To me, it was like saying "define variable A to be 0.8 of variable A" before A is even set. The documentation in the answer below resolves this confusion by explicitly saying there is an initial value on which all computations are performed (and I see that you implicitly referred to this initial value in your reply). Thanks.
    – agronskiy
    Apr 24, 2018 at 3:40

1 Answer 1

6

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

1
  • Greaaat! Exactly what I was looking for! Thanks!
    – agronskiy
    Apr 23, 2018 at 22:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.