为什么font-family会影响按钮之间的空间? [英] Why font-family affects the space between the buttons?

查看:136
本文介绍了为什么font-family会影响按钮之间的空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解决方案

这是因为每种字体都有不同的宽度,空格字符。你已经知道了内联块的空格问题。因此,当您设置Arial时,这些空格会从浏览器的默认字体(或任何其他宽度不同的字体)稍微改变它们的宽度,这是我的情况下的Times New Roman。

现在,为什么会发生在第2个和第3个框之间,不是第一和第二个?我很确定它归结为基于输入的单词的宽度舍入像素值,似乎有一个伪子像素渲染呈现在背景中,但十进制值在最终渲染过程中四舍五入。看看会发生什么,如果你使用Arial和打印地狱堆溢出,而不是你的堆栈溢出 - 差距看起来一样。



另一点证明这是一个四舍五入问题,是各种页面缩放级别之间的差距的变化。在HTML中处理小数时,在布局中获取这些像素不匹配是相当常见的。缩放增加了另一个分割/倍增阶段,这会进一步改变核心值,导致最终布局中的完全不可预测的行为。


DEMO

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

Consider the following example:

HTML:

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

CSS:

.my-class {
  display: inline-block;
  margin-left: -4px;   /* Remove the space between inline elements */
  border: 1px solid #cccccc;
  padding: 20px;
}

which produces:

But, if I add:

body {
  font-family: Arial;
}

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

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

PLAYGROUND HERE

解决方案

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.

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.

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.

这篇关于为什么font-family会影响按钮之间的空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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