Search code examples
htmlcsscss-grid

css grid creates empty rows and columns


I have a grid with 2 areas. It works fine with grid-template-areas: "list details". Why does it create a 3x2 grid if I specify only one area: grid-template-areas: "list"? And why does it stick the second area in the bottom right track?

https://jsfiddle.net/o5txebkc/

#main {
    display: grid;
    grid-template-areas:
        "list";
}

    #main .list {
        background: yellow;
        grid-area: list;
    }

    #main .details {
        background: green;
        grid-area: details;
    }
<main id="main">
  <article class="list">
    <ul>
      <li>one</li>
      <li>two</li>
    </ul>
  </article>

  <article class="details">
    <h3>Details</h3>
    <p>
      some details
    </p>
  </article>
</main>


Solution

  • Screenshot of grid in Developer Tools

    Using Developer Tools to highlight the grid and show the lines, I see that "details" is positioned outside of the explicit grid. (Notice the negative line numbers.) This behavior changes if you remove grid-area: details; from the .details { } class rule.

    Because you defined a grid-area for "details" but did not give it an explicit position on the grid, it is placed into the implicit grid at the closest row and column where it is not touching the named lines.


    The implicit and explicit grid

    • Explicit grid: Created using grid-template[-*].
    • Implicit grid: Extends the defined explicit grid when content is placed outside of that grid, such as into rows by drawing additional grid lines.


    Counting backwards

    We can also count backwards from the block and inline end of the grid... These lines can be addressed as -1, and you can count back from there – so the second last line is -2. It is worth noting that the final line is the final line of the explicit grid ... and does not take into account any rows or columns added in the implicit grid outside of that.


    'grid-area' values

    If a name is given as a <custom-ident>, only lines with that name are counted. If not enough lines with that name exist, all implicit grid lines are assumed to have that name for the purpose of finding this position.