Home > Blockchain >  How to create a CSS grid with 5 blocks (2 on row 1, 3 on row 2)
How to create a CSS grid with 5 blocks (2 on row 1, 3 on row 2)

Time:09-27

I want to create layout with format where in the first line I will have 2 elements and in the second 3 elements, I have the opposite version but cant revert the rows.

.container {
  display: grid;
  grid-template-columns: repeat(6, 40px);
  grid-auto-rows: 80px;
  grid-gap: 10px;
}

.block {
  background-color: red;
  grid-column-end: span 2;
}

.block:nth-last-child(-n 2) {
  background: blue;
  grid-column-start: 2
}
.block:nth-last-child(-n 1) {
  background: blue;

  grid-column-start: 4
}
<div class="container">
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
</div>

CodePudding user response:

Just add the CSS for the third block as:

.block:nth-last-child(-n 3) {
  background: blue;
  grid-column-start: 1
}

And this to center the red blocks:

.block:nth-child(1) {
  grid-column-start: 2;
}

DEMO

.container {
  display: grid;
  grid-template-columns: repeat(6, 40px);
  grid-auto-rows: 80px;
  grid-gap: 10px;
}

.block {
  background-color: red;
  grid-column-end: span 2;
}
.block:nth-child(1) {
  grid-column-start: 2;
}
.block:nth-last-child(-n 3) {
  background: blue;
  grid-column-start: 1;
}
.block:nth-last-child(-n 2) {
  background: blue;
  grid-column-start: 3
}
.block:nth-last-child(-n 1) {
  background: blue;

  grid-column-start: 5
}
<div class="container">
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
</div>

  • Related