CSS grid layout with different flowing and filling order

Viewed 71

Is there a way to make a horizontally flexible grid (or any grid-like) layout to fill column-wise first?

The rule is basically:

  1. Check if items fit into a row, make new row if they don't (works as if the layout is row wrap constrained by container width)
  2. Fill cells column-wise (works as if the layout is column wrap constrained into a given row amount decided on step #1)

 

With a decreasing container width, it visually work more or less like following:

| 1 | 2 | 3 | 4 | 5 | 6 | 7 |

-----------------------------

|  1  |  3  |  5  |  7  |
|  2  |  4  |  6  |

-------------------------

|   1  |   4  |   7  |
|   2  |   5  |
|   3  |   6  |

-----------------------

|    1   |    5   |
|    2   |    6   |
|    3   |    7   |
|    4   |
1 Answers

You can try using column properties instead of flexbox or grid. Set the column-count: 7; and specify the column width. Also Firefox has a strange bug with column layout and overflow: hidden; will fixed it in the .item class.

.item {
  overflow: hidden; /* Fixed strange behaviour for Firefox */
}

body {
  background-color: #131b24;
}

.container {
  --size: 100px;
  width: fit-content;
  column-width: var(--size);
  column-count: 7;
  column-gap: 0;
}

.item {
  width: var(--size);
  height: var(--size);
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden; /* for Firefox */
  border: 2px solid red;
  break-inside: avoid;
}

.item h1 {
  font-size: 2em;
  color: white;
}
<div class="container">
  <div class="item">
    <h1>1</h1>
  </div>
  <div class="item">
    <h1>2</h1>
  </div>
  <div class="item">
    <h1>3</h1>
  </div>
  <div class="item">
    <h1>4</h1>
  </div>
  <div class="item">
    <h1>5</h1>
  </div>
  <div class="item">
    <h1>6</h1>
  </div>
  <div class="item">
    <h1>7</h1>
  </div>
</div>

Related