Home > Mobile >  Use css Grid to divide unknow number of items into two columns, but list in column order
Use css Grid to divide unknow number of items into two columns, but list in column order

Time:01-21

I have a number of items I wish to divide into two even columns.

I have an example enter image description here

But what I want is for the items to "flow" down the columns, ie they will be in the order

 1        4
 2        5
 3        6

I thought the property grid-auto-flow would do this, but I can't get it to do what I am after

Is there an easy way I can do this (preferably with css grid)?

CodePudding user response:

It doesn't always have to be the latest layout technique; sometimes there already is an older one that was specifically created to get the job at hand done.

That being said, consider using columns, which does what you want, out of the box:

#parent {
  columns: 2;
}

.item {
  break-inside: avoid;
  margin: 5px;
  height: 40px;
  width: 50px;
  background: green;
  color: white;
}
<div id="parent">
  <div >1</div>
  <div >2</div>
  <div >3</div>
  <div >4</div>
  <div >5</div>
  <div >6</div>
  <div >7</div>
</div>

Important Side Note: As @Yousaf has pointed out, this can lead to a single item being spread to two columns, because the browsers tries to make sure both columns are about the same height. To avoid that, simply use

break-inside: avoid;

for the column items.

CodePudding user response:

Yes you can do this without needing to change the HTML.

CSS lets you say which column you want a particular item to be in.

In your case you want the odd ones to be in column 1 and the even ones to be in column 2 so you can use grid-column: 1 on the odd ones, and grid-column: 2 on the even ones.

#parent {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-auto-flow: row;
}

.item {
  margin: 5px;
  height: 40px;
  width: 50px;
  background: green;
  color: white;
}

.item:nth-child(odd) {
  grid-column: 1;
}

.item:nth-child(even) {
  grid-column: 2;
}
<div id="parent">
  <div >1</div>
  <div >2</div>
  <div >3</div>
  <div >4</div>
  <div >5</div>
  <div >6</div>
</div>

CodePudding user response:

Use grid-auto-flow: column; if you want it to flow that way. Although you'll need to set your row templates to 1fr 1fr 1fr.

#parent {
  display: grid;
  grid-template-rows: repeat(3, 1fr);
  grid-auto-flow: column;
}

.item {
  margin: 5px;
  height: 40px;
  width: 50px;
  background: green;
  color: white;
}
<div id="parent">
  <div >1</div>
  <div >2</div>
  <div >3</div>
  <div >4</div>
  <div >5</div>
  <div >6</div>
</div>

More on grid-auto-flow here.

  •  Tags:  
  • Related