Mark Hildreth
Mark Hildreth

Reputation: 43071

How can I auto-flow: column but specify the columns

I would like to have a CSS grid that renders the items column by column, where the max number of columns and rows is not assumed. I have below the best version that I was able to come up with, although with some workarounds that I am hoping to not be required:

.grid {
  display: grid;
  grid-auto-flow: column;
  grid-template-rows: repeat(4, 1fr);
}

.item {
  margin: 1em;
}

.column {
  display: contents;
}

.clear {
  grid-row-end: -1;
}
<div class="grid">
  <div class="column">
    <div class="item">A1</div>
    <div class="item">A2</div>
    <div class="clear"></div>
  </div>
  <div class="column">
    <div class="item">B1</div>
    <div class="item">B2</div>
    <div class="item">B3</div>
    <div class="clear"></div>
  </div>
  <div class="column">
    <div class="item">C1</div>
    <div class="clear"></div>
  </div>
</div>

As you can see:

Note that just having each column lay itself out (using something like flexbox or CSS Columns) will not work, as it is important that the grid items (which may have varying heights) remain aligned with their horizontal neighbors.

Upvotes: 1

Views: 59

Answers (1)

Temani Afif
Temani Afif

Reputation: 272816

You can easily get rid of the clear element by setting the row of the first element of each column then you can consider the trick of a big number of rows but with auto sizing and not 1fr. You won't have any blank space if you don't use row gaps:

.grid {
  display: grid;
  grid-auto-flow: column;
  grid-template-rows: repeat(1000, auto);
}

.item {
  margin: 1em;
}

.column {
  display: contents;
}

.column .item:first-child {
  grid-row: 1;
}
<div class="grid">
  <div class="column">
    <div class="item">A1</div>
    <div class="item">A2</div>
  </div>
  <div class="column">
    <div class="item">B1</div>
    <div class="item">B2</div>
    <div class="item">B3</div>
  </div>
  <div class="column">
    <div class="item">C1</div>
  </div>
</div>

Upvotes: 1

Related Questions