Caution: rem in @media query definitions ignore your font-size

Posted 23 days ago. Visible to the public.

Note

Using rem only ever makes sense when the root font size is dynamic, i.e. you leave control to the user. Either by a) respecting their user agent defaults, or by b) offering multiple root font sizes in your application.

By defining @media queries in rem, they will accommodate to the root font size of your page. At a larger root font, breakpoints will be at larger widths, scaling with the font. However, there is a catch in case b) mentioned in the note above.

Relative length units in media queries are based on the initial value, which means that units are never based on results of declarations. For example, in HTML, the em unit is relative to the initial value of font-size, defined by the user agent or the user’s preferences, not any styling on the page. Source Show archive.org snapshot

This means that you should only use rem units in @media queries when you're relying on the font size provided by the user agent (mostly it's 16px). In other words: if you set a root font size, do not express @media queries in rem.

Example

html {
  font-size: 20px;
}

@media (min-width: 100rem) {
  // Styles for large screens
}

You would expect the styles for large screens to apply from 2000px viewport width. However, in line with the spec, browsers with a default font size of 16px will apply them from 1600px viewport width.

Dominik Schöler
Last edit
15 days ago
Dominik Schöler
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2024-04-15 06:15)