Search code examples
htmlcsscss-grid

CSS Grid items overflow wrapper


Can someone please explain me why the usage of grid-gap in the wrapper overflows the items? The manual just says it ADDS space between the items, not extending them in any way or something.

CODEPEN: Source

body {
  margin: 0
}

.wrapper {
  display: grid;
  grid-template-columns: 50% 50%;
  grid-gap: 10px;
  border: 1px solid black;
  padding: 10px;
  margin: 0 auto;
  max-width: 800px;
}

.header {
  grid-column: 1/3;
  background: red
}

.footer {
  grid-column: 1/3;
  background: green
}

.item {
  padding: 10px
}

.content {
  height: 180px
}

.image {
  background: yellow
}

.desc {
  background: blue
}

@media screen and (min-width:768px) {
  .content {
    grid-column: 1/3
  }
}
<div class="wrapper">
  <div class="item header">Header</div>
  <div class="item content image">Image</div>
  <div class="item content desc">Description</div>
  <div class="item content image">Image</div>
  <div class="item content desc">Description</div>
  <div class="item footer">Footer</div>
</div>


Solution

  • So the reason is in fact that you are setting the columns to use 50% of the width of the parent, which also includes the gaps. For CSS Grid it would be best to use fr units to specify equal width columns.

    In your case, if you use 1fr 1fr or repeat(2, 1fr) instead of 50% 50%, you actually tell the grid to set its columns to 1 fraction of the available space, this will take the gaps into account and not overflow the parent.

    body {
      margin: 0
    }
    
    .wrapper {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      grid-gap: 10px;
      border: 1px solid black;
      padding: 10px;
      margin: 0 auto;
      max-width: 800px;
    }
    
    .header {
      grid-column: 1/3;
      background: red
    }
    
    .footer {
      grid-column: 1/3;
      background: green
    }
    
    .item {
      padding: 10px
    }
    
    .content {
      height: 180px
    }
    
    .image {
      background: yellow
    }
    
    .desc {
      background: blue
    }
    
    @media screen and (min-width:768px) {
      .content {
        grid-column: 1/3
      }
    }
    <div class="wrapper">
    
      <div class="item header">Header</div>
    
      <div class="item content image">Image</div>
      <div class="item content desc">Description</div>
    
      <div class="item content image">Image</div>
      <div class="item content desc">Description</div>
    
      <div class="item footer">Footer</div>
    
    </div>