CSS网格大小相等的列 [英] CSS grid equal size columns
问题描述
我正在尝试创建3个div,每个div包含1个
标签,并使用CSS网格将所有3个div以相等的宽度分布在同一行上。
I'm trying to create 3 divs each containing 1 <p>-tag and distribute all 3 on the same row with an equal width using CSS grid.
大多数消息人士说,我应该使用 grid-template-columns
来实现这一目标。有人说要去 1fr 1fr 1fr
,有人说要 repeat(3,1fr)
,还有一些人说 repeat(3,auto)
。
Most sources say that I should use grid-template-columns
to achieve this. Some say to go for 1fr 1fr 1fr
, some say repeat(3, 1fr)
, and yet more say repeat(3, auto)
.
结果是相同的。 3个div结束于同一行,但是它们的宽度根据其内容的宽度而变化。有没有一种方法可以强制所有3个div具有相同的宽度,如果内容太宽,只需使用下一行?
The result is the same. The 3 divs end up on the same line, but their widths change depending on the width of their content. Is there a way to force all 3 divs to have the same width and simply use the next line if the content is too wide?
该代码段应显示我的情况m in。
The snippet should show the situation I'm in.
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
.content {
margin: 2em;
}
<div class="grid-container">
<div class="content">
<p>TESTTESTTESTTESTTESTTESTTESTTESTTES</p>
</div>
<div class="content">
<p>TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTES</p>
</div>
<div class="content">
<p>TESTESTTESTTESTTESTTESTTESTTESTTESTTESTTES</p>
</div>
</div>
推荐答案
您的网格很好-内容就是这里的问题。
Your grid is fine - the content is the problem here.
您可以尝试断字
或溢出
作为一种解决方法:
You can try word-break
or overflow
as a workaround:
断字
解决方案:
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
border: 2px dotted green;
}
.content {
margin: 2em;
border: 2px solid red;
}
.content p {
word-break: break-word;
}
<div class="grid-container">
<div class="content">
<p>TESTTESTTESTTESTTESTTESTTESTTESTTES</p>
</div>
<div class="content">
<p>TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTES</p>
</div>
<div class="content">
<p>TESTESTTESTTESTTESTTESTTESTTESTTESTTESTTES</p>
</div>
</div>
溢出
解决方案:
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
border: 2px dotted green;
}
.content {
margin: 2em;
border: 2px solid red;
overflow: auto;
}
<div class="grid-container">
<div class="content">
<p>TESTTESTTESTTESTTESTTESTTESTTESTTES</p>
</div>
<div class="content">
<p>TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTES</p>
</div>
<div class="content">
<p>TESTESTTESTTESTTESTTESTTESTTESTTESTTESTTES</p>
</div>
</div>
编辑:显然, word-break:break-word;
在Firefox中不起作用-谢谢,@ Yaakov Ainspan。再次提醒您应在多个浏览器中测试代码。 断字:全部;
可以代替。
Apparently, word-break: break-word;
does not work in Firefox - thanks, @Yaakov Ainspan. Another reminder that you should test your code in multiple browsers. word-break: break-all;
can be used instead.
这篇关于CSS网格大小相等的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!