CSS grid square layout

Minio picture Minio · Feb 28, 2019 · Viewed 14.5k times · Source

I am trying to create grid/layout consists of squares. Four squares in each row. Squares can't distort on screen resize. Width and height must be the same all the time (I don't want fixed values). I must use CSS grid. Can anyone help me ?

.container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-gap: 5px;
}
.container div {
  background-color: red;
}
<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

Answer

Fabrizio Calderan picture Fabrizio Calderan · Feb 28, 2019

With CSS only you could use a pseudoelement to keep always the aspect ratio to 1:1 , e.g.

.container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-gap: 5px;
}
.container div {
  background-color: red;
}

.container div::before {
  content: "";
  padding-bottom: 100%;
  display: inline-block;
  vertical-align: top;
}
<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>