0

I'm aware can set the number of columns a grid item spans using:

grid-column: span 2;

But is it possible to have CSS grid do this automatically only if there is space available?

So in the case of the mockup below, if there are three items they each take up a full column, but if there are two, the last item will expand to fill up the empty column.

enter image description here

.grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 25px;
}

.grid-item {
  padding: 50px;
  color: white;
  background-color: lightpink;
}
<div class="grid">
  <div class="grid-item"></div>
  <div class="grid-item"></div>
  <div class="grid-item"></div>
</div>

<br />
<hr />
<br />

<div class="grid">
  <div class="grid-item"></div>
  <div class="grid-item">I should take up two columns</div>
</div>
D-Money
  • 2,375
  • 13
  • 27

1 Answers1

-1

Instead of hardcoding and using span 2 (which is useful sometimes) you can use grid-column: 2 / -1;. It says that your grid column should start from the second col and should span until it has the space (exactly what you want)

.grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 25px;
}

.grid-item {
  padding: 50px;
  color: white;
  background-color: lightpink;
}

.grid-item-2 {
  grid-column: 2 / -1;
}
<div class="grid">
  <div class="grid-item"></div>
  <div class="grid-item"></div>
  <div class="grid-item"></div>
</div>

<br />
<hr />
<br />

<div class="grid">
  <div class="grid-item"></div>
  <div class="grid-item grid-item-2">I should take up two columns</div>
</div>
Arun Bohra
  • 144
  • 8