TransWikia.com

Create 3x3 responsive layout with CSS grid

Stack Overflow Asked by Smithy on December 7, 2020

I would like to create a 3×3 grid that shrinks boxes one under the other when on smaller screen. Boxes should be always the perfect square.

Also, the last two boxes (8 + 9) should be only one longer rectangle on larger screen, but take the same space as now. Is CSS grid a way to go here? Here’s what I got:

body {
  background: lightblue;
}

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  grid-gap: 20px;
}

.grid div {
  width: 100%;
  height: 100%;
  background: white;
  padding: .5em;
}
  <div class="grid">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div>join</div>
    <div>us</div>
  </div>

One Answer

You can do something like this -

body {
  background: lightblue;
}

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  grid-gap: 20px;
}

.grid div {
  width: 100%;
  height: 0%;
  padding-bottom: 100%;
  background: white;
}

.grid div:last-child:nth-child(3n - 1) {
  grid-column: span 2;
  height: auto;
  padding-bottom: 0;
}

@media (max-width: 400px) {
  .grid {
    grid-template-columns: 1fr;
  }
}
<div class="grid">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div>join us</div>

</div>

...and then add media query to make it responsive.

Edit:

What I did is -

  1. changed height of .grid div to 0 and added padding-bottom: 100% to make it a perfect square.
  2. added .grid div:last-child:nth-child(3n - 1) to target the last child and make it fill the rest of the grid.

Edit 2: Added media query.

Correct answer by Debsmita Paul on December 7, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP