Warm tip: This article is reproduced from serverfault.com, please click

How to define a font size that scales with browser zoom level?

发布于 2020-11-27 23:24:50

For my webapp I'm attempting to create a div which maintains the same size regardless of zoom level. That is, if I measure the div with a real-world ruler and it is 3 inches wide, then regardless of how far I zoom in or out, it will always be 3 inches wide.

I've noticed that if I define the font-size of the root html document, then I can use the relativistic rem for that div and all of its child elements.

The closest I've gotten so far is setting font-size: 1vh; on the html element. Then, whenever I use rem units, the div and its contents stay the same size regardless of zoom level, which is perfect.

The only issue with this solution is that it scales with viewport height. That is, if you make your window shorter, the element will decrease in height. Similarly, if you make the window taller then the element will increase in height.

This is bad, because for all my users regardless of their monitor size I want this item to be the same size. That is, it should be 3 inches wide for everyone regardless of their viewport width, height, monitor size, or whatever.

The only thing I could think of to solve this is to somehow detect browser zoom levels and then use Javascript to modify the html element's font-size property, but that approach seems extremely finicky and not very cross-browser in how well it works.

Questioner
Ryan Peschel
Viewed
0
Ryan Peschel 2020-11-28 09:32:42

I figured this out and it seems to work. Likely going to use this unless someone comes up with a better solution:

function scaleFontSize() {
  let scaledFontSize = (16 / window.devicePixelRatio) + "px";
  
  document.documentElement.style["font-size"] = scaledFontSize;
}

scaleFontSize();

window.addEventListener('resize', scaleFontSize, true);