Search code examples
htmlcsscss-grid

CSS Grid - Rows to be same height (with a max height)


I am trying to make my rows have the same height in a CSS grid, but at the same time, there should be a max height specified by vh. What I would want, is that if there are 4 rows, with a max height of 100vh, and the current largest height out of the 4 rows is 70vh, I would want all the rows to be 70vh. However, if the largest height is supposedly 120vh, I want all the height of the rows to be 100vh. Is there a way to do so? Below is my code thus far, I am new to CSS grid so do help me out! If there are any simpler ways to achieve what I want to do, please help guide me, thank you!

.project-grid {
    display: grid;
    grid-template-columns: 100%;
    grid-template-rows: 1fr 1fr 1fr 1fr 1fr;
    row-gap: 1%;
    grid-template-areas: "card" "activities" "requirements" "quotations" "notations"
}

.card-row {
    grid-area: card;
}

.activities-box {
    grid-area: activities;
    overflow: auto;
}

.requirements-box {
    grid-area: requirements;
    overflow: auto;
}

.quotations-box {
    grid-area: quotations;
    overflow: auto;
}

.notations-box {
    grid-area: notations;
    overflow: auto;
}

With this, the rows all follow the same largest height, but there is no max height set.


Solution

  • Simply set max-height to the grid items:

    .box {
      display: grid;
      grid-template-columns: 100%;
      grid-auto-rows: 1fr;
      row-gap: 5px;
    }
    
    .box > * {
      max-height:100vh;
      overflow:auto;
      border:2px solid red;
      background:#f2f2f2;
      box-sizing:border-box;
    }
    <div class="box">
      <div><div style="height:50vh"></div></div>
      <div></div>
      <div></div>
      <div></div>
    </div>

    And with content bigger than 100vh;

    .box {
      display: grid;
      grid-template-columns: 100%;
      grid-auto-rows: 1fr;
      row-gap: 5px;
    }
    
    .box > * {
      max-height:100vh;
      overflow:auto;
      border:2px solid red;
      background:#f2f2f2;
      box-sizing:border-box;
    }
    
    body {
      margin:0;
    }
    <div class="box">
      <div><div style="height:130vh"></div></div>
      <div></div>
      <div></div>
      <div></div>
    </div>