Search code examples
cssgrid

CSS Grid Layout Gap Box Sizing


I have a CSS grid that occupies 100% width and 100% height of a window (the body element has display: grid;). The grid has row and column templates and elements which occupy 100% of their allocated space. However, when I add a grid-gap to the grid, it makes the grid too large for the window, forcing scrollbars to appear. How can I stop the grid-gap from adding to the dimensions of the grid - similar to how box-sizing: border-box; stops padding from adding to the dimensions of an element? Instead, I want the gaps to shrink the cells of the grid.

Thanks. like this


Solution

  • It works same as if you used box-sizing: border-box and padding as you can see in this demo. Height is set to 100vh and you can see that if you remove or add grid-gap there is no scrollbar, you just need to remove margin from body.

    body {
      margin: 0;
    }
    .grid {
      display: grid;
      height: 100vh;
      grid-gap: 20px;
      background: #FF7D7D;
      grid-template-columns: 1fr 2fr; /* Use Fractions, don't use % or vw */ 
    }
    .grid > div {
      background: black;
      color: white;
    }
    div.a, div.d {
      color: black;
      background: white;
    }
    <div class="grid">
      <div class="a">A</div>
      <div class="b">B</div>
      <div class="c">C</div>
      <div class="d">D</div>
    </div>