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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)