首页 > 解决方案 > CSS Grid - unnecessary word break

问题描述

I have a problem with CSS grid.

In the following snippet extracted from the codebase, I have a very simple HTML structure with grid layout. Content is set to break-word to prevent text from overflowing. Event though there is enough space for the text to NOT get broken, it does create a line break just before the last letter.

My understanding was that in grid layout, by default, items are calculated to fit the content as much as possible, which is somehow not the case in this example.

Removing padding from content or margins from grid item does solve the issue, but margin is there for centering and padding is also needed.

Is there any property I have to or can use to solve this problem?

P.S. To my knowledge, the bug is not present in Firefox, I have found it in Chrome and Safari so far.

.grid {
  display: grid;
  grid-template-columns: auto;
}

.item {
  margin: 0 auto;
}

p {
  word-break: break-word;
  padding: 0 4%;
}
<div class="grid">
  <div class="item">
    <p>HOTEL</p>
    <p>GRAND</p>
  </div>
</div>

标签: cssgoogle-chromesafaricss-grid

解决方案


这不是错误,而是复杂的计算。

有一种循环来计算产生问题的元素的最终宽度。首先考虑内容(基于您使用的属性的收缩以适应行为)计算宽度,然后使用带有填充的百分比值将考虑计算的宽度1。最后,我们将从创建分词的宽度中减少计算出的填充。

这将发生在最小值的情况下,因为在所有情况下,宽度总是小于包含最长单词所需的宽度:

.grid {
  display: grid;
  grid-template-columns: auto;
}
.item {
  margin:auto;
  border:1px solid;
}
.pad p {
  word-break: break-word;
  padding: 0 1%;
}
<div class="grid">
  <div class="item">
    <p>HOTEL</p>
    <p>I_WILL_FOR_SURE_BREAK</p>
  </div>
</div>

<div class="grid">
  <div class="item pad">
    <p>HOTEL</p>
    <p>I_WILL_FOR_SURE_BREAK</p>
  </div>
</div>

如您所见,第一个带有填充的网格被缩小到其内容,第二个网格具有完全相同的宽度,并且填充正在创建换行符。


一个简单的解决方法是使用像素值而不是百分比,以防您知道所需的值:

.grid {
  display: grid;
  grid-template-columns: auto;
  justify-content:center;
}

.item {
  margin:auto;
  border:1px solid;
}

.pad p {
  word-break: break-word;
  padding: 0 20px;
}
<div class="grid">
  <div class="item">
    <p>HOTEL</p>
    <p>I_WILL_NOT_BREAK</p>
  </div>
</div>

<div class="grid">
  <div class="item pad">
    <p>HOTEL</p>
    <p>I_WILL_NOT_BREAK</p>
  </div>
</div>


为什么你在firefox上看不到这个?

仅仅因为break-word那里不支持(https://developer.mozilla.org/en-US/docs/Web/CSS/word-break

在此处输入图像描述

所以你会有一个溢出而不是一个分词。如果您使用以下命令,您可能会在 Firefox 上注意到这种行为break-all

.grid {
  display: grid;
  grid-template-columns: auto;
}
.item {
  margin:auto;
  border:1px solid;
}
p {
  word-break: break-all;
  padding: 0 1%;
}
<div class="grid">
  <div class="item">
    <p>HOTEL</p>
    <p>I_WILL_FOR_SURE_BREAK</p>
  </div>
</div>


1 : padding 的大小,相对于包含块的宽度的百分比。参考


推荐阅读