csscss-grid

How to make CSS grid fill even with element spanning 2 columns


If I have a grid like this where an element spans 2 columns

.parent {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-auto-rows: 100px;
  grid-gap: 1rem;
}

.element.green {
  grid-column: 1 / -1;
  background: green;
}

.element {
  background: red;
}
<div class="parent">
  <div class="element"></div>
  <div class="element green"></div>
  <div class="element"></div>
  <div class="element"></div>
  <div class="element"></div>
  <div class="element"></div>
</div>

How can I make it so that the 3rd element fills the empty space in the first row?

I am trying to make this work with only CSS but have no idea how.


Solution

  • Add the grid-auto-flow: dense; property to the .parent container. This changes the grid placement algorithm, allowing it to fill in earlier gaps in the layout if possible.

    This property has been a baseline feature since 2017.

    Reference on MDN — CSS/grid-auto-flow

    Updated CSS:

    .parent {
        display: grid;
        grid-template-columns: 1fr 1fr;
        grid-auto-rows: 100px;
        grid-gap: 1rem;
        grid-auto-flow: dense;
    }
    
    .element.green {
        grid-column: 1 / -1;
        background: green;
    }
    
    .element {
        background: red;
    }
    <div class="parent">
        <div class="element"></div>
        <div class="element green"></div>
        <div class="element"></div>
        <div class="element"></div>
        <div class="element"></div>
        <div class="element"></div>
    </div>