CSS Grid Layout Gap Box Sizing

Freddy Tuxworth picture Freddy Tuxworth · Apr 27, 2017 · Viewed 7.3k times · Source

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

Answer

Henning Fischer picture Henning Fischer · Nov 9, 2017

When you use "fr" it works.

<section>
    <article class="a">A</article>
    <article class="b">B</article>
    <article class="c">C</article>
    <article class="d">D</article>
</section>

section {
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-auto-flow: column;
    grid-gap: 20px;

    border: 10px solid blue;

    article {
        background-color: tomato;

        &.d {
            grid-column: 2; 
            grid-row-start: 1; 
            grid-row-end: 4;

            background-color: olive;
        }
    }
}