CSS grid with negative margins making element height grow with it

Viewed 22

I'm trying to emulate the following into CSS grid:

enter image description here

Essentially a 7 card layout, with negative margins.

To achieve this, I've created a 3x3 grid and have used grid-area to get cards 1 and 4 to span 2 columns.

Then, I've applied negative margins on cards 2 and 3 to achieve what's in the image.

However, as you will see in my demo, it causes the heights of the cards to grow with it. For example, card 3 ends where card 2 does.

:root {
  --black: #000000;
  --white: #FFFFFF;
}

body {
  background-color: var(--black);
  max-width: 940px;
  margin: 0 auto;
  padding: 600px 0;
}

.grid {
  display: grid;
  gap: 80px;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
  counter-reset: items;
}

.cell {
  background-color: var(--white);
  padding: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.cell:before {
  counter-increment: items;
  content: counter(items);
  font-size: 24px;
  font-weight: 700;
}
.cell:first-child {
  grid-area: span 2/span 1;
}
.cell:nth-child(2) {
  margin-top: -250px;
}
.cell:nth-child(3) {
  margin-top: -500px;
}
.cell:nth-child(4) {
  grid-area: span 2/span 1;
}
<div class="grid">
  <div class="cell"></div>
  <div class="cell"></div>
  <div class="cell"></div>
  <div class="cell"></div>
  <div class="cell"></div>
  <div class="cell"></div>
  <div class="cell"></div>
</div>

Are negative margins the best way to achieve this type of design?

1 Answers

You could look on it as a 3 column 6 row grid, with each item spanning two rows.

Here's a simple example with each item being specifically placed in the relevant column and row.

:root {
  --black: #000000;
  --white: #FFFFFF;
}

body {
  background-color: var(--black);
  max-width: 940px;
  margin: 0 auto;
}

.grid {
  display: grid;
  grid-column-gap: 80px;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(6, 1fr);
  counter-reset: items;
}

.cell {
  background-color: var(--white);
  padding: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  grid-row: var(--r) / span 2;
  grid-column: var(--c);
  box-sizing: border-box;
}

.cell:before {
  counter-increment: items;
  content: counter(items);
  font-size: 24px;
  font-weight: 700;
}

.cell:nth-child(1) {
  --r: 3;
  --c: 1;
}

.cell:nth-child(2) {
  --r: 2;
  --c: 2;
}

.cell:nth-child(3) {
  --r: 1;
  --c: 3;
}

.cell:nth-child(4) {
  --r: 5;
  --c: 1;
}

.cell:nth-child(5) {
  --r: 4;
  --c: 2;
}

.cell:nth-child(6) {
  --r: 3;
  --c: 3;
}

.cell:nth-child(7) {
  --r: 5;
  --c: 3;
}
<div class="grid">
  <div class="cell"></div>
  <div class="cell"></div>
  <div class="cell"></div>
  <div class="cell"></div>
  <div class="cell"></div>
  <div class="cell"></div>
  <div class="cell"></div>
</div>

Related