skip to Main Content

Not looking as expected:

.cont {

    display: grid;
    grid-template-rows: 33% 33% 33%;
    grid-template-columns: 33% 33% 33%;
}

so obviously the expected outcome would be a tic-tac-toe like grid of equal squares. However the height flattens to the content of each div, i have 9 of them. I tried everything setting height to 100% in container div and individual divs, it always flattens regardless of content. Problem is different squares will be empty or have content at different times. If I set a specific height on the rows, ex. 250px it works fine, but it will not work with percentages for some reason. I just want 9 equal squares regardless of browser height and width in px. You would think this would not be so difficult.

I did not include the rest of the code because it is obvious 1 container with 9 divs in it.

2

Answers


  1. If you want the container to fill the height, I would use min-height: 100vh so that it will start at the full height of the screen.

    I added children inside the container for demonstration purposes. The grid children will automatically fill their grid cell.

    Also, if you would like the columns and rows to be evenly distributed, you can use repeat(), which will set the amount of columns/rows and the size of each as well.

    You can read more about repeat() here.

    .cont {
      background-color: #171717;
      min-height: 100vh;
        display: grid;
        grid-template-rows: repeat(3, 1fr);
        grid-template-columns: repeat(3, 1fr);
      grid-gap: 0.25rem;
    }
    
    .testing-box {
      background-color: white;
    }
    <div class="cont">
      <div class="testing-box"></div>
      <div class="testing-box"></div>
      <div class="testing-box"></div>
      <div class="testing-box"></div>
      <div class="testing-box"></div>
      <div class="testing-box"></div>
      <div class="testing-box"></div>
      <div class="testing-box"></div>
      <div class="testing-box"></div>
    </div>
    Login or Signup to reply.
  2. To fill the screen (and not exceed it) the maximum size of the columns/rows is 1/3 of the viewport height.

    So we set the columns widths to 33.33vh (1/3 of viewport height) and use aspect-ratio on the children to ensure they stay square.

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    .cont {
      display: grid;
      grid-template-columns: repeat(3, 33.3vh);
    }
    
    .square {
      aspect-ratio: 1 /1;
      outline: 1px solid green;
    }
    <div class="cont">
      <div class="square"></div>
      <div class="square"></div>
      <div class="square"></div>
      <div class="square"></div>
      <div class="square"></div>
      <div class="square"></div>
      <div class="square"></div>
      <div class="square"></div>
      <div class="square"></div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search