Search code examples
htmlcsscss-grid

Responsive grid of squares fitting window height


I am trying to create responsive grid of squares (3x3 and then 5x5). The code below correctly creates a grid of squares that get smaller as the window shrinks. However, I would like to limit the maximum height of the entire container to the height of the browser window. Which means I have to limit the height of a single square. But when I set min-height and max-height to square, the width is not changing.

.square-container {
  display: grid;
  grid-template-columns:repeat(3,1fr);
  grid-gap: 10px;
}

.square {
  border: 1px solid;
  border-radius: 5px;
  aspect-ratio:1/1;
}
<div class="square-container">
  <div class="square">1</div>
  <div class="square">2</div>
  <div class="square">3</div>
  <div class="square">4</div>
  <div class="square">5</div>
  <div class="square">6</div>
  <div class="square">7</div>
  <div class="square">8</div>
  <div class="square">9</div>
</div>


Solution

  • Apply the logic to the container

    .square-container {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      grid-auto-rows: 1fr; /* equal rows*/
      gap: 10px;
      aspect-ratio: 1; /* make the container a square */
      /* limit the width and height */
      max-height: 100vh;
      max-width: 100%;
      /* center horizontally */
      margin: auto;
    }
    
    .square {
      border: 1px solid;
      border-radius: 5px;=
      /* full width and height*/
      height: 100%;
      width: 100%;
      /**/
      box-sizing: border-box;
    }
    
    body {
      margin: 0;
    }
    <div class="square-container">
      <div class="square">1</div>
      <div class="square">2</div>
      <div class="square">3</div>
      <div class="square">4</div>
      <div class="square">5</div>
      <div class="square">6</div>
      <div class="square">7</div>
      <div class="square">8</div>
      <div class="square">9</div>
    </div>