如何定义随浏览器缩放级别缩放的字体大小? [英] How to define a font size that scales with browser zoom level?

查看:79
本文介绍了如何定义随浏览器缩放级别缩放的字体大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的Web应用程序,我尝试创建一个div,无论缩放级别如何,该div都保持相同的大小.也就是说,如果我使用现实世界的标尺测量div,并且它的宽度为3英寸,那么无论我放大或缩小多远,它的宽度始终都是3英寸.

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.

我注意到,如果我定义根 html 文档的 font-size ,则可以将相对论的 rem 用于该div及其所有子元素.

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.

到目前为止,我最接近的是在 html 元素上设置 font-size:1vh; .然后,每当我使用 rem 单位时,无论缩放级别如何,div及其内容都将保持相同大小,这是完美的.

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.

这很不好,因为对于我的所有用户,无论他们的显示器大小如何,我都希望该项目的大小相同.也就是说,无论所有人的视口宽度,高度,监视器大小或其他任何内容,它都应为3英寸宽.

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.

我唯一想解决的方法是以某种方式检测浏览器的缩放级别,然后使用Javascript修改 html 元素的 font-size 属性,但该方法似乎极其挑剔,但浏览器的运作方式不是很好.

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);

这篇关于如何定义随浏览器缩放级别缩放的字体大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆