Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a CSS grid with alternating single and double rows?

Tags:

html

css

css-grid

I have a list with an unlimited number of items. I need to make a grid like this:

enter image description here

I tried to do it, but it doesn't work and I get a different result:

.list {
  display: grid;
  gap: 20px;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  
}

.item {
  min-height: 100px;
  background-color: #0299b2;
}

.item:nth-child(3n + 1) {
  min-height: 220px;
  grid-row-end: span 2;
  background-color: #20B202;
}
<div class="list">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>
  <div class="item">6</div>
  <div class="item">7</div>
  <div class="item">8</div>
  <div class="item">9</div>
  ...
</div>
like image 893
flockast Avatar asked Oct 22 '25 00:10

flockast


1 Answers

Your pattern repeat each 6 elements so do it like below.

I also have a detailed article about such technique and more CSS tricks if you want to dig deeper: https://css-tricks.com/exploring-css-grids-implicit-grid-and-auto-placement-powers

.list {
  display: grid;
  gap: 20px;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  grid-auto-flow: dense; /* don't forget this to fill all the cells */
}

.item {
  min-height: 100px;
  background:red;
  color:#fff;
  font-size: 30px;
}

.item:nth-child(6n + 1),
.item:nth-child(6n + 6){
  grid-row: span 2; /* 2 rows for 1st and 6th item */
  background: blue;
}
.item:nth-child(6n + 5) {
  grid-column: 1; /* first column for 5 */
}
<div class="list">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>
  <div class="item">6</div>
  <div class="item">7</div>
  <div class="item">8</div>
  <div class="item">9</div>
</div>
like image 181
Temani Afif Avatar answered Oct 24 '25 14:10

Temani Afif



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!