DEV Community

โ†’ Ale Narvaja
โ†’ Ale Narvaja

Posted on

Solving a layout issue with `grid-auto-flow: column`

In a recent project, I encountered a layout issue that was elegantly solved by the CSS Grid property grid-auto-flow: column. Let's dive into the problem and the solution.

The Problem

I was working on a responsive design where I needed to display a set of data items. On smaller screens, these items should stack vertically, but on larger screens, they should arrange themselves into a grid. The catch was, I wanted the items to fill up the columns first before moving on to the next row.

The default behavior of CSS Grid is to fill up the rows first (row-based placement), which wasn't what I wanted. Here's a simplified version of my initial CSS:

<section class="data">
  <div class="data__item">Item 1</div>
  <div class="data__item">Item 2</div>
  <div class="data__item">Item 3</div>
  <div class="data__item">Item 4</div>
  <div class="data__item">Item 5</div>
  <div class="data__item">Item 6</div>
</section>
Enter fullscreen mode Exit fullscreen mode
.data {
  display: grid;
  gap: var(--space-m);
  grid-template-columns: repeat(2, auto);
  grid-template-rows: repeat(3, auto);
}
Enter fullscreen mode Exit fullscreen mode

This render this layout:

Grid layout row-based

The Solution

Enter grid-auto-flow: column. This property alters the default behavior of CSS Grid, making it fill up the columns before the rows (column-based placement). Here's how I modified my CSS:

.data {
  display: grid;
  gap: var(--space-m);
  grid-template-columns: repeat(2, auto);
  grid-template-rows: repeat(3, auto);

  /* Add this property ๐Ÿ‘‡๐Ÿฝ */
  grid-auto-flow: column;
}
Enter fullscreen mode Exit fullscreen mode

Grid layout column-based

With grid-auto-flow: column, the grid items now fill up vertically in each column before moving on to the next column. This was exactly the behavior I needed for my layout.

Conclusion

CSS Grid's grid-auto-flow: column is a powerful tool for controlling the placement of grid items. It's a great example of how a single CSS property can drastically simplify a complex layout problem. Happy coding!

More info

MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-flow

Codepen

Top comments (0)