tolec
tolec

Reputation: 133

Place items in pairs in two rows using css grid

I'm trying to render items in a specific order, look at the picture: enter image description here

i.e. there is an infinite number of items, by columns, each column has two items. Do you have any ideas how to code this using grids or flexbox or any other way (maybe by combining them)? I know I can do it with tables, but I'm trying to avoid them this time.

Upvotes: 7

Views: 13185

Answers (2)

Dung Le
Dung Le

Reputation: 96

.box{
display: flex;
 flex-wrap: wrap;
width: 100%;
justify-content: space-around;
}
span{
display: inline-block;
margin-bottom: 1rem;
text-align: center;
width: 16%;
height: 5rem;
background-color: #555;
color: #f0f0f0;
}
span:nth-of-type(1), span:nth-of-type(2), span:nth-of-type(5), span:nth-of-type(6), span:nth-of-type(9), span:nth-of-type(10)      {
     order: 0;
}
span:nth-of-type(3), span:nth-of-type(4), span:nth-of-type(7), span:nth-of-type(8), span:nth-of-type(11), span:nth-of-type(12){
     order: 1;
}
<div class="box">
 <span>1</span>
 <span>2</span>
 <span>3</span>
 <span>4</span>
 <span>5</span>
 <span>6</span>
 <span>7</span>
 <span>8</span>
 <span>9</span>
 <span>10</span>
 <span>11</span>
 <span>12</span>

</div>

Upvotes: 1

Temani Afif
Temani Afif

Reputation: 273979

nth-child() can help here

.box {
  display:grid;
  grid-auto-flow:column dense; /* column flow with "dense" to fill all the cells */
  grid-template-rows:50px 50px; /* 2 rows */
  grid-auto-columns:50px;
}
.box span:nth-child(4n + 2) { /* this will do the trick*/
   grid-row:1; /* we make 2 in the first row and 3 will be pushed to second row */
}

/* irrelevant styles */
.box {
  counter-reset:num;
  grid-gap:5px;

}
.box span {
  background:yellow;
  font-size:25px;
}

.box span::before {
  content:counter(num);
  counter-increment:num;
}
<div class="box">
 <span></span>
 <span></span>
 <span></span>
 <span></span>
 <span></span>
 <span></span>
 <span></span>
 <span></span>
 <span></span>
 <span></span>
 <span></span>
 <span></span>
 <span></span>
 <span></span>
 <span></span>
 <span></span>
</div>

Upvotes: 8

Related Questions