为什么字体家族会在按钮之间偶尔增加1px的间距? [英] Why font-family sporadically adds 1px gap between buttons?

查看:76
本文介绍了为什么字体家族会在按钮之间偶尔增加1px的间距?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请仔细阅读问题.与如何删除内联块元素之间的空间不同.

Please read the question carefully. It's not the same as the one about How to remove the space between inline-block elements.

考虑以下HTML:

body {
  /* font-family: Arial; */
}

.my-class {
  display: inline-block;
  margin: 0 0 0 -4px;
  background-color: transparent;
  border: 1px solid #ccc;
  padding: 20px;
}

<div>
  <button class="my-class">Hello</button>
  <button class="my-class">Stack</button>
  <button class="my-class">Overflow</button>
</div>

哪个会产生:

但是,如果我添加:

body {
  font-family: Arial;
}

第二个和第三个按钮之间的间距为1px:

it results in a 1px space between the second and third buttons:

问题是:为什么在body中添加font-family会影响按钮之间的间距?

The question is: Why adding font-family to the body affects the space between the buttons?

推荐答案

之所以会发生这种情况,是因为每种字体都具有不同的宽度,即使对于空格字符也是如此.您已经知道内联块的空白问题.因此,当您设置Arial时,这些空格的宽度会与浏览器的默认字体(或其他具有不同宽度的字体)稍有不同,在我的情况下为Times New Roman.

It happens because each font has different width, even for the space character. You already know about the whitespace issues with inline-blocks. So, when you set Arial, those whitespaces change their width slightly from the browser's default font (or any other font with different width), which is Times New Roman in my case.

查看设置等宽字体时所做的更改有多大.

See how drastic the change is when you set the monospace font.

现在,为什么发生在第二个和第三个盒子之间,而不是第一个和第二个盒子之间?我很确定它可以归结为根据输入的单词的宽度舍入像素值,似乎在背景中存在伪子像素渲染,而十进制值在最终渲染过程中被舍入.查看使用Arial并打印地狱堆栈溢出"而不是"Hello堆栈溢出"会发生什么情况-间隙看起来相同.因此,这只是不希望的巧合.

Now, why it happens between the 2nd and the 3rd box and not the 1st and the 2nd one? I'm pretty sure it comes down to rounding pixel values based on the width of the words entered, seems like there is a pseudo sub-pixel rendering present in the background, yet the decimal values get rounded in the final render process. See what happens if you use Arial and print Hell Stack Overflow instead of Hello Stack Overflow - the gaps look the same. So, it's just an undesired coincidence.

证明这是一个四舍五入问题的另一点是各个页面缩放级别之间的间隙变化.在HTML中处理小数时,在布局中获得这些像素不匹配是很常见的.缩放增加了另一个除法/乘法阶段,这进一步改变了核心值,从而导致最终布局中的行为完全不可预测.

Another point that proves this is a rounding issue is the change in the gaps across various page zoom levels. It's fairly common to get these pixel mismatches in the layout when dealing with decimals in HTML. Zooming adds another dividing/multiplication stage, which changes the core values even further, resulting in completely unpredictable behaviour in the final layout.

这篇关于为什么字体家族会在按钮之间偶尔增加1px的间距?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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