Search code examples
csscss-grid

How to expand parent height in nested CSS grids when children expand


I have some nested CSS grids where children grids expand past the parent grid height.

I deleted my code to the bare minimum so that I could see what was causing this but I have not been able to identify where the problem code is or how to make the parent height responsive to the children.

I suspect my main problem to be somewhere in this code here but you can see the problem here https://jsfiddle.net/bgp7fzjm/2/

.grid-container {
  background-color: #080808;
  display: grid;
  grid-template-areas:
  "site-card"
  "project-card";
  justify-content: space-evenly;
  max-width: 100%;
  height: 100%;
}

#site-card {
  grid-area: site-card;
  display: grid;
  grid-template-areas:
  "site1"
  "site2"
  "site3";
  grid-column-gap: 4%;
  grid-row-gap: 4%;
}

Ideally, the parent grid expands with the children and the children do not overflow past the background color.


Solution

  • The problem is that you use percentage for grid-row-gap. This won't work if you don't set a specific height to the parent grid wrapper. Percentages ( in this case ) are depending on the dimensions of the parent. Because if not, 4% of what ? The grid won't know.

    If you don't want to set a specific height, you can use px for the gap.

    .grid-container {
      background-color: #080808;
      display: grid;
      grid-template-areas: "site-card" "project-card";
      justify-content: space-evenly;
      max-width: 100%;
      height: auto;
    }
    
    #site-card {
      grid-area: site-card;
      display: grid;
      grid-template-areas: "site1" "site2" "site3";
      grid-column-gap: 4%;
      grid-row-gap: 10px;
    }
    
    #site1 {
      grid-area: site1;
    }
    
    #site2 {
      grid-area: site2;
    }
    
    #site3 {
      grid-area: site3;
    }
    
    .card {
      width: 90px;
      height: 90px;
      background-color: red;
      max-width: 100%;
    }
    <main>
      <div class="grid-container">
        <section id="site-card">
          <div class="card" id="site1">
    
    
          </div>
          <div class="card" id="site2">
    
    
          </div>
          <div class="card" id="site3">
    
    
          </div>
        </section>
      </div>
    </main>