How to make a 7 item diamond grid with CSS grid?

Viewed 108

How can I replicate the followig using CSS Grid?

desired

So far I have the following:

.parent{
   display: grid;
   gap: 1.5em;
   grid-template-columns: repeat(3, 1fr);
}

But this leaves the first column with 3 items (not desired)...

outcome

Also, how could one align-items: center; the first and last column to give that diamond effect?

2 Answers

You can use a simplified code like below:

.box{
  background: #123456;
}
.wrapper {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-auto-rows: 100px;
  gap:15px;
}
.box:last-child {
  grid-column:2;
}
.box:nth-child(1),
.box:nth-child(3),
.box:nth-child(4),
.box:nth-child(6) {
  transform:translateY(50%);
}
<div class="wrapper">
   <div class="box"></div>
   <div class="box"></div>
   <div class="box"></div>
   <div class="box"></div>
   <div class="box"></div>
   <div class="box"></div>
   <div class="box"></div>
</div>

First you need to set class/id for every box you want to have, then just set start and end values for both columns and rows for every box.

The trick I used, to get desired output, is that I didnt go for 3 rows, but 6. While middle column has taken all the rows, left and right columns have first and last row empty.

Example in codepen: https://codepen.io/FITDaniel/pen/abVawrw

.box{
  background: #123456;
  margin: 15px;
}
.wrapper {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(6, 50px);
}
.box1 {
   grid-column-start: 1;
   grid-column-end: 2;
   grid-row-start: 2;
   grid-row-end: 4;
}
.box2 {
   grid-column-start: 1;
   grid-column-end: 2;
   grid-row-start: 4;
   grid-row-end: 6;
}
.box3 {
   grid-column-start: 2;
   grid-column-end: 3;
   grid-row-start: 1;
   grid-row-end: 3;
}
.box4 {
   grid-column-start: 2;
   grid-column-end: 3;
   grid-row-start: 3;
   grid-row-end: 5;
}
.box5 {
   grid-column-start: 2;
   grid-column-end: 3;
   grid-row-start: 5;
   grid-row-end: 7;
}
.box6 {
   grid-column-start: 3;
   grid-column-end: 4;
   grid-row-start: 2;
   grid-row-end: 4;
}
.box7 {
   grid-column-start: 3;
   grid-column-end: 4;
   grid-row-start: 4;
   grid-row-end: 6;
}
<div class="wrapper">
   <div class="box1 box"></div>
   <div class="box2 box"></div>
   <div class="box3 box"></div>
   <div class="box4 box"></div>
   <div class="box5 box"></div>
   <div class="box6 box"></div>
   <div class="box7 box"></div>
</div>

Related