Search code examples
htmlcssresponsive-designmedia-queries

Using rems to specify breakpoints in media queries


I am using rems to specify the breakpoints in media queries as follows

@media screen and (min-width: 30rem) {}

If the base font size is not defined in body {} it will inherit the browser default font size. I'v heard using rems is a best practice. My question is if user changes the browser default font size then media query will not target the expected screen size.

eg:

30rem (width of view port) = 480px (targeted viewport) / 16px (browser default)

and user changes font size to 14px then

34rem (width of view port) = 480px (targeted viewport) / 14px (user changed)

as a solution the font size can be defined in the body tag. But again that is similar to specifying the view port size in pixels and what makes rems better than pixels.


Solution

  • You are correct that if the base font size is 16px, then

    @media screen and (min-width: 30rem) {}
    

    and

    @media screen and (min-width: 480px) {} 
    

    will both give the same results.

    If you zoom in with your browser they will also give the same result.

    As you point out though, if a user resets their browser font size then the 2 media queries give different results.

    There's a good pen on Codepen to illustrate this.

    Note that in this pen, if you set your browser font size larger or smaller than 16px the green em based box is either smaller or larger than your viewport, so this wouldn't be ideal in responsive design.

    So I think px vs rem in the media query depends partly on your personal preference and partly on the specifics of your design.

    FWIW, one easy option for responsive design is to use px in the media query and rems (or ems) for the styling, e.g.

    /* Document level adjustments */
    html {
      font-size: 17px;
    }
    @media (max-width: 900px) {
      html { font-size: 15px; }
    }
    @media (max-width: 400px) {
      html { font-size: 13px; }
    }
    
    /* Modules will scale with document */
    .header {
      font-size: 1.5rem;
    }
    .footer {
      font-size: 0.75rem;
    }
    .sidebar {
      font-size: 0.85rem;
    }
    
    /* Type will scale with modules */
    h1 {
      font-size: 3em;
    }
    h2 {
      font-size: 2.5em;
    }
    h3 {
      font-size: 2em;
    }
    

    source: https://css-tricks.com/rems-ems/