Grid areas and the element that occupies them aren’t necessarily the same size.

That's a good little thing to know about CSS grid.

I'm sure that is obvious to many of you, but I'm writing this because it was very much not obvious to me for far too long.

Let's take a close look.

There are two players to get into your mind here:

  1. The grid area, as created by the parent element with display: grid;
  2. The element itself, like a <div>, that goes into that grid area.

For example, say we set up a mega simple grid like this:

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 1rem;
}

If we put four grid items in there, here's what it looks like when inspecting it in Firefox DevTools:

Now let's target one of those grid items and give it a background-color:

The grid area and the element are the same size!

There is a very specific reason for that though. It's because the default value for justify-items and align-items is stretch. The value of stretch literally stretches the item to fill the grid area.

But there are several reasons why the element might not fill a grid area:

  1. On the grid parent, justify-items or align-items is some non-stretch value.
  2. On the grid element, align-self or justify-self is some non-stretch value.
  3. On the grid element, if height or width is constrained.

Check it:

Who cares?

I dunno it just feels useful to know that when placing an element in a grid area, that's just the starting point for layout. It'll fill the area by default, but it doesn't have to. It could be smaller or bigger. It could be aligned into any of the corners or centered.

Perhaps the most interesting limitation is that you can't target the grid area itself. If you want to take advantage of alignment, for example, you're giving up the promise of filling the entire grid area. So you can't apply a background and know it will cover that whole grid area anymore. If you need to take advantage of alignment and apply a covering background, you'll need to leave it to stretch, make the new element display: grid; also, and use that for alignment.