css - 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>
解决方案
这不是错误,而是复杂的计算。
有一种循环来计算产生问题的元素的最终宽度。首先考虑内容(基于您使用的属性的收缩以适应行为)计算宽度,然后使用带有填充的百分比值将考虑计算的宽度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 的大小,相对于包含块的宽度的百分比。参考
推荐阅读
- javascript - 我如何使用递归函数在 javascript 中推送数组
- wordpress - 在我的 wampserver localhost 错误上运行 Wordpress?
- python-3.x - Telethon 问题:RuntimeWarning:从未等待协程“send_message”
- html - flex 列中的行高不相等
- python - 如何在字典中找到列表的最大值
- python - Pyinstaller,--onefile 在尝试将 .py 转换为 venv 中的 .exe 时出现错误
- c - 如何找到整体运行时间?
- youtube - Cobalt 是在哪种架构下构建的?
- ios - AVPlayer 在将 PlayerItem 加载到播放器之前开始缓冲它
- machine-learning - 由于类不平衡,在对训练数据进行下采样后评估测试集上的模型结果