5

This is a Q&A on achieving a column wrap after a specific number of child elements using css Grid.

HTML mockup

<div class="parent">
  <div class="child">1</div>
  <div class="child">2</div>
  <div class="child">3</div>
  <div class="child">4</div>
  <div class="child">5</div>
  <div class="child">6</div>
  .....
  <div class="child">n</div>
</div>

And the required layout is something like,

1  7   13
2  8   14
3  9   .
4  10  .
5  11  n
6  12

After a specific number of items(6 in this case), the remaining contents should be wrapped onto a new column.

Gibin Ealias
  • 2,751
  • 5
  • 21
  • 39

2 Answers2

8

You can achieve this with a combination of grid-template-rows and grid-auto-flow with a CSS like:

.parent {
    display: grid;
    grid-template-rows: repeat(6, auto);
    grid-gap: 10px;
    grid-auto-flow: column;
}

Demo

Gibin Ealias
  • 2,751
  • 5
  • 21
  • 39
Divyanshu Maithani
  • 13,908
  • 2
  • 36
  • 47
  • Yes, you are right. You solution seems to be a better one. Thanks a lot. I have a small correction that `grid-template-rows: repeat(6, auto);` would be better way of handling this else the `height` would be restricted. Please suggest. – Gibin Ealias Feb 19 '18 at 15:13
  • 1
    Agreed, I've also updated the codepen accordingly :) – Divyanshu Maithani Feb 20 '18 at 08:16
0

The conventional way of achieving this layout is by setting a height to the parent element so that when an overflow occurs, the contents gets wrapped to a new column.

This method is unreliable if we are unsure of the child elements' contents as it causes an overlap/overflow if the contents exceed the pre-defined height of the container.

To overcome this, we could using Javascript to measure the height of the contents and assigning the largest of it to the parent, which would require a DOM manipulation.

CSS Grid solution

With the introduction of CSS Grid, we now have a better solution with grid-row-start property along with the :nth-child(xn + y) CSS3 selector.

.parent {
  display: grid;
}

.child:nth-child(6n + 2) {
  grid-row-start: 2;
}

.child:nth-child(6n + 3) {
  grid-row-start: 3;
}

.child:nth-child(6n + 4) {
  grid-row-start: 4;
}

.child:nth-child(6n + 5) {
  grid-row-start: 5;
}

.child:nth-child(6n) {
  grid-row-start: 6;
}

CODEPEN

Hope this helps.

Gibin Ealias
  • 2,751
  • 5
  • 21
  • 39