Search code examples
htmlcsszooming

Chrome does not keep consistent rem units on zoom-in


I want to make use of rem units in CSS, so I set a font-size to my <html> tag so I can set child elements with rem dimensions. The problem however is that when you zoom in on Chrome, the font-size style seems to change relative to zoom level, which causes the dimensions of elements with rem units to change relative to the level of zoom. See the example below in Chrome:

window.onresize = function() {
  console.log(getComputedStyle(document.body.parentElement, null).getPropertyValue("font-size"));
}
html {
    font-size: 7px;
}
body {
    font-size: 2em;
}
.box {
    width: 10rem;
    height: 10rem;
    background: red;
}
<html>
    <head>
    </head>
    <body>
        <div class="box"></div>
        <p>foo bar baz</p>
    </body>
</html>

To see the effect, press to run the snippet, then click to view full screen, and zoom out in Chrome. When zoomed out past 75% you'll see that the box does not change size on your screen, while the whole page is supposed to change zoom level.

Also, as you can see in the console, the computed style for <html> is font-size: 12px when the zoom level is 25%, which is a direct contradiction to the css styles specified.

This does not happen in Firefox, so I would like to know: how can I use rem units while keeping consistent behaviour across browsers when zooming?


Solution

  • The solution I found was to simply multiply the original font-size by 2, and then divide all rem sizes by 2 as well, because then the font-size at 50% will be 7px again. In other situations, that may not work, but repeating this trick again might fix

    The problem seems to be that Chrome decides that its rendered font sizes cannot be less than 3px, which means that any font size below 12px will gradually creep towards being rendered at 3px, but will never shrink to smaller than that.

    window.onresize = function() {
      console.log(getComputedStyle(document.body.parentElement, null).getPropertyValue("font-size"));
    }
    html {
        font-size: 14px;
    }
    body {
        font-size: 1em;
    }
    .box {
        width: 5rem;
        height: 5rem;
        background: red;
    }
    <html>
        <head>
        </head>
        <body>
            <div class="box"></div>
            <p>foo bar baz</p>
        </body>
    </html>

    Of course I'm still interested to see what the actual reasons behind any of this are, and if there are better solutions.