为什么 "inline-block" trim 元素最后的 space 呢?

Why does "inline-block" trim the space at the end inside the element?

问题是,当我在 <p> 标签内有多个 <span> 元素并给那些 <span> 一个 inline-block 的 CSS 时,[ <span> 末尾的 =32=] 被 inline-block 修剪。

有人可以解释为什么会发生这种行为吗?

.container {
  width: 500px;
  margin: auto;
  font-size: 2em;
  border: solid 1px red;
}

.merge {
  white-space: nowrap;
  display: inline-block;
}
<div class="container">
  <p>Lorem ipsum dolor sit amet consectetur <span class="merge">adipisicing elit, </span><span class="merge">Provident, </span><span class="merge">amet, </span><span class="merge">facere, </span><span class="merge">modi itaque, </span><span class="merge">praesentium, </span><span class="merge">nihil quam? </span><span class="merge">Nostrum, </span><span class="merge">aut assumenda, </span><span class="merge">Doloribus vitae, </span><span class="merge">necessitatibus, </span><span class="merge">iusto, </span><span class="merge">debitis, </span><span class="merge">aliquam, </span><span class="merge">odit, </span><span class="merge">pariatur, </span><span class="merge">fuga, </span><span class="merge">mollitia, </span><span class="merge">magni, </span></p>
</div>

在每个内联块中,前导和尾随空格被视为无关紧要且不会呈现,遵循与 section 16.6.1 of CSS2 中常规块元素相同的规则。这是因为内联块和常规块一样,是块容器盒,每个都建立自己的内联格式化上下文。

具体来说,以下适用于“每一行”的步骤实际上适用于每个内联块,因为它可以说包含自己的“文本行”。内部文本并不都占据与内联块本身相同的行框,而是内联块控制的内联格式化上下文。

As each line is laid out,

  1. If a space (U+0020) at the beginning of a line has 'white-space' set to 'normal', 'nowrap', or 'pre-line', it is removed.

  2. [...]

  3. If a space (U+0020) at the end of a line has 'white-space' set to 'normal', 'nowrap', or 'pre-line', it is also removed.

这与默认的 display: inline 不同,默认的 display: inline 会导致所有文本呈现在同一行框上。因此默认跨度中的 none 空间将被修剪,除非它们位于一行的开头或结尾。

您可以在 span 元素中添加额外的填充来解决此问题。

示例:

.merge {
  white-space: nowrap;
  display: inline-block;
  padding: 0 5px;
}