Search code examples
htmlcsscss-grid

Why is the CSS grid extending beyond the parent?


I am in an Angular 15 component using CSS grid. When the grid has one row, the grid bottom is the same as the 'services-section' bottom. When I have more than one row, the grid extends beyond the bottom of 'services-section'. Plus, with each row, that bottom extension grows a little more.

Setting overflow to auto adds scroll bars to the div. Setting overflow to hidden, truncates the last row. Both of these are not desired. Height, min-height 100%, auto, etc is no go either.

How do I get that grid container to behave? https://jsfiddle.net/eflat123/vq08u7gb/7/

  <div class="grid" style="min-height: fit-content;">
    <mat-card class="card">
      <mat-card-content><p>My Service 1</p><p>1 hour</p></mat-card-content>
    </mat-card>
    <mat-card class="card">
      <mat-card-content><p>My Service 2</p><p>1 hour</p></mat-card-content>
    </mat-card>
    <mat-card class="card">
      <mat-card-content><p>My Service 3</p><p>1 hour</p></mat-card-content>
    </mat-card>
    <mat-card class="card">
      <mat-card-content><p>My Service 4</p><p>1 hour</p></mat-card-content>
    </mat-card>
    <mat-card class="card">
      <mat-card-content><p>My Service 5</p><p>1 hour</p></mat-card-content>
    </mat-card>
    <mat-card class="card">
      <mat-card-content><p>My Service 6</p><p>1 hour</p></mat-card-content>
    </mat-card>
    <mat-card class="card">
      <mat-card-content><p>My Service 7</p><p>1 hour</p></mat-card-content>
    </mat-card>
  </div>
</div>

<style>
  .services-section {
    border: 1px solid blue;
  }
  .grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    padding: 0 1.5em;
    grid-row-gap: 7%;
    grid-column-gap: 5%;
  }
</style>

Solution

  • the "grid-row-gap: 7%;" is the cause of the issue, change it to something other than a percent, this will fix your problem

    grid-row-gap: 2em;

    also remove or change the

    style="height: 100%"

    to

    style="min-height: 100%"

    in the parent to allow the grid to grow when adding cards