Read more

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

Dominik Schöler
April 15, 2024Software engineer at makandra GmbH

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

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more 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.

Posted by Dominik Schöler to makandra dev (2024-04-15 08:15)