Here's the issue, When I have multiple <span>
elements inside a <p>
tag and give those <span>
a CSS of inline-block
, the space at the end of the <span>
is trimmed by the inline-block
.
Could someone explain why this behavior is happening?
.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>
Within each inline-block, leading and trailing whitespace is treated as insignificant and not rendered, following the same rules as for regular block elements in section 16.6.1 of CSS2. This is because inline-blocks, like regular blocks, are block container boxes, each establishing its own inline formatting context.
Specifically, the following steps that apply to "each line" actually apply to every inline-block as it contains its own "line of text" so to speak. The inner text does not all occupy the same line boxes as the inline-blocks themselves, but the inline formatting contexts governed by the inline-blocks.
As each line is laid out,
If a space (U+0020) at the beginning of a line has 'white-space' set to 'normal', 'nowrap', or 'pre-line', it is removed.
[...]
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.
This is different from the default display: inline
, which does cause all text to be rendered on the same line boxes. So none of the spaces in the default spans would be trimmed, unless they were at the start or end of a line.