Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS grid equal size columns

Tags:

css

css-grid

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>
like image 384
Rins Avatar asked Feb 01 '26 23:02

Rins


2 Answers

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.

like image 69
fen1x Avatar answered Feb 03 '26 12:02

fen1x


Try:

grid-template-columns: repeat(3, minmax(0, 1fr));
like image 41
Giedrius nesvarbu Avatar answered Feb 03 '26 12:02

Giedrius nesvarbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!