Search code examples
htmlcsscss-grid

Why does `height: 100%` value 'work' for child tags of grid-items?


Consider this:

#grid-container {
  display: grid;
  height: 200px;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(2, 1fr);
}

.grid-item > p {
    height: 100%;
}
<div id="grid-container" style="display: grid">
  <div class="grid-item">
    <p>I am p.</p>
  </div>
    <div class="grid-item">
    <p>I am p.</p>
  </div>
    <div class="grid-item">
    <p>I am p.</p>
  </div>
    <div class="grid-item">
    <p>I am p.</p>
  </div>
</div>

Because of the CSS line:

    .grid-item > p {
        height: 100%;
    }

The p tags have the same height as the grid-items. This is great, as this is what I want. My question is, how is this working?

I thought that if the parent element/containing-block's height wasn't specified explicitly (surely grid-items, here, have height: auto;) then % (on the child element) won't work (and something like height: auto will be used instead).

Additionally, I know/think that if the parent is absolutely positioned, % will work (return a percentage value of what parent's actual height is).

What is making % work for children of grid-items?


Solution

  • This is related to the stretch default alignment of grid item.

    Note: Since formulas calculated using only definite sizes, such as the stretch fit formula, are also definite, the size of a grid item which is stretched is also considered definite. ref

    As you can see, the size is definite so it can be used as reference for percentage.


    Same logic for flexbox:

    If the flex item has align-self: stretch, redo layout for its contents, treating this used size as its definite cross size so that percentage-sized children can be resolved ref

    Related question with non-intuive percentage behavior: https://stackoverflow.com/a/52137966/8620333