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.
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).
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?
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:
word-break solution:
.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>
overflow solution:
.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>
EDIT: 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.
Try:
grid-template-columns: repeat(3, minmax(0, 1fr));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With