1

I am trying to understand how to achieve a layout that takes two columns in the first row and three columns in the second row, third row, and so on.

<section>
   <div>1</div>
   <div>2</div>
   <div>3</div>
   <div>4</div>
   <div>5</div>
   <div>6</div>
   <div>7</div>
   <div>8</div>
</section>

//CSS
section {
   display: grid;
   grid-template-columns: 1fr 1fr;
}

The above code will give me two-column layout but how to modify it to achieve mentioned layout.

Sagar Sinha
  • 375
  • 2
  • 8
  • 26

2 Answers2

6

You can try like below:

section {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  grid-gap: 5px;
}

section div {
  grid-column: span 3;
  height: 50px;
  background: red;
}

section div:nth-child(n + 3) {
  grid-column: span 2;
}
<section>
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
</section>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
6

This is what I wanted actually.

section {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 5px;
}

div {
  height: 50px;
  background: red;
}
div:first-child {
  grid-column: 1 / 3;
}
<section>
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
</section>
Sagar Sinha
  • 375
  • 2
  • 8
  • 26