How to make the last row of items take up the remaining space in CSS Grid?
P粉434996845
P粉434996845 2023-10-20 20:39:37
0
1
840

Is there a way to force all items in the last row of the grid to fill that row, no matter how many they have?

I don't know the number of items in the grid, so I can't target them directly. I tried using grid-auto-flow:ensemble but it didn't really help.

This is a visualization of my problem: :


div {
  margin:20px auto;
  width: 400px;
  background: #d8d8d8;
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(3, 1fr);
}
span {
  height: 50px;
  background: blue;
}
<div>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>  
</div>
 


P粉434996845
P粉434996845

reply all(1)
P粉418351692

This is entirely possible with CSS Grid by combining the CSS rules nth-child and nth-last-of type. The only thing to note is that the number of columns needs to be known in advance.

.grid {
    display: grid;
    grid-template-columns: auto auto auto;
    justify-items: start;
    grid-gap: 10px;
}

.grid div {
  border: 1px solid #ccc;
  width: 100%;
}

.grid > *:nth-child(3n-1) {
  justify-self: center;
  text-align: center;
}

.grid > *:nth-child(3n) {
  justify-self: end;
  text-align: right;
}

.grid > *:nth-child(3n-1):nth-last-of-type(1) {
  border-color: red;
  grid-column: span 2;
}

.grid > *:nth-child(3n-2):nth-last-of-type(1) {
  border-color: red;
  grid-column: span 3;
}
<div class="grid">
  <div>text</div>
  <div>TEXT</div>
  <div>text</div>
  <div>text</div>
  <div>TEXT</div>
  <div>text</div>
  <div>text</div>
  <div>TEXT</div>
</div>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template