Media queries PX vs EM vs REM

stckpete picture stckpete · Apr 16, 2015 · Viewed 9.8k times · Source

Can anyone explain why my media queries break when converting them FROM px TO ems

In the body of my document, I have included the following rule font-size: 62.5%, Therefore I would assume that I could convert my media query to FROM 650px to 65em? Changing my media queries to ems breaks the layout

As an alternative, can I convert the media query to REMS with a pixel fallback ?? that said, I have no idea how to do this

@media screen and (min-width: 650px) {     
  body {
    font-size: 62%;
    background-color: #364759;
    background-repeat: repeat-x;
    background: url("bg.gif");
  }
    
  #wrapper, footer {
    width: 80%;
    max-width: 1050px;
    margin: 0 auto;
  }
} // end media query 

many thanks, P

Answer

Florian Rivoal picture Florian Rivoal · Apr 18, 2015

Section 1.3 of the media queries spec says:

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

Similarly, the section 2 says:

Unless another feature explicitly specifies that it affects the resolution of Media Queries, it is never necessary to apply a style sheet in order to evaluate expressions.

So your font-size: 62.5% rule has no effect with regards to media queries, and 1em is still 16px, not 10px.

The reason things are this way is that doing otherwise would cause loops, which is something CSS cannot deal with. Try to think of what this example would do if we didn't have this rule:

body { font-size: 10000px; }
@media (min-width: 1em) {
  body { font-size: 1px; }
}

1em would be gigantic, so the media query would match, so 1em would be small, so the media query wouldn't match, so 1em would be gigantic, so...