Search code examples
htmlcssmedia-queriesrootfont-size

Changing font-size on root doesn't affect @media queries


I'm working in a page that has

html {
    font-size: 62.5%;
}

That means 1rem = 10px instead of 1rem = 16px So far, so good.

The problem is that it doesn't affect @media queries.

/*
it should change at 600px and not 960px.
the @media ignores the 62.5%;
*/
@media (min-width: 60rem) {
    .el {
        background: blue;
    }
}

Check this codepen to see the issue.

http://codepen.io/sandrina-p/pen/bqGZjE

I tested on a retina monitor, with Chrome and Firefox. On Safari the issue doesn't happen.

Any solution?


Solution

  • I found the issue. In @media you need to use em and it will always read the default browser size, ignoring your custom font-size. The same doesn't happen with rem. So in this case, you need to set 37.5em (600/16), and it will change the at 600px in every browser including safari.

    https://zellwk.com/blog/media-query-units/

    (...) the only unit that performed consistently across all four browsers is em. There aren’t any differences between em and rem with the exception of bugs found on Safari. (...) Unfortunately, px media queries remained at 400px in the third experiment, which makes it a no-go if you intend to support users who change their browser’s font-size value. Hence, my conclusion after these experiments is: Use em media queries.

    @media screen and (max-width: 37.5em) {
        .el {
            background: blue;
        }
    }