Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

.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>

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading