search

Home  >  Q&A  >  body text

How to make the last row of items take up the remaining space in CSS Grid?

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粉434996845P粉434996845445 days ago834

reply all(1)I'll reply

  • P粉418351692

    P粉4183516922023-10-21 11:05:17

    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>

    reply
    0
  • Cancelreply