且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

内联块div不会缩小到内容

更新时间:2023-02-16 18:27:37

这是一个有趣的问题.

请考虑以下简化示例.

我有一个内联块元素.textbox,其max-width为300px, 设计用于强制文字换行.

I have an inline-block element .textbox with a max-width of 300px, designed to force the text to wrap.

在第一行中,我添加了white-space: nowrap,以将文本保留在一行中,并强制其从元素中溢出.

In the first line, I added a white-space: nowrap to keep the text on a single line and to force it to overflow out of the element.

如果运行以下代码段,则应看到第二个框的右边缘与单词"onto"重合,因此浏览器中的文本流算法将强制以"onto"开头的文本流入如预期的那样,第二行.

If you run the snippet below, you should see that the right edge of the second box coincides with the word "onto", so the text flow algorithm in the browser will force the text, starting with "onto" to flow into the second line, as expected.

现在,正如您所指出的,在前一个单词("wraaaa .... ap")的右边留有空白.该空间对应于单词"onto"的长度,直至包含元素的最大宽度.

Now, as you noted, there is white space left over to the right of the preceding word ("wraaaa....ap"). This space corresponds to the length of the word "onto" up to the max-width of the containing element.

浏览器不会计算将要流到第二行的字符串/单词留下的空白量,因此,它将.textbox的宽度保留为max-width定义的值.

Browsers do not compute the amount of white space left by the string/word that is about to flow onto the second line, therefore, it leaves the width of the .textbox to the value defined by max-width.

因此,这说明了额外空间是如何产生的.但是,无法使用CSS强制浏览器退格"并消除右侧的空白.

So, this demonstrates how the extra space originates. However, there is no way using CSS of forcing the browser to "backspace" and eliminate the hanging white space to the right.

付出更多的努力,您也许可以提出一个JavaScript/jQuery修复程序,但这将是一个不同的练习,也许社区中的其他成员可能会寻求进一步的答案.

With a lot more effort, you might be able to come up with a JavaScript/jQuery fix, but that would be a different exercise, which perhaps some other member of the community may pursue to further the answer along.

我还应该注意,在Firefox中也会出现相同的问题.

I should also note the the same problem arises in Firefox.

此外,如果尝试显示table-celltableinline-table,也会显示相同的效果.

Furthermore, the same effect manifests itself if you try display table-cell and table and inline-table.

.textbox {
  outline: 1px dotted gray;
  display: inline-block;
  max-width: 300px;
  margin: 2px 0; /* for demo only */
}
.textbox.fix {
  white-space: nowrap;
}

<div class="textbox fix">Some words that can wraaaaaaaaaaaaaaaap onto a second line as needed.</div>
<br>
<div class="textbox">Some words that can wraaaaaaaaaaaaaaaap onto a second line as needed.</div>