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.
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);
i thought
max-width
could solve the issue but i am wrong. at the moment i cant think of any other solution.