Why do block elements with margin auto behave differently inside a grid?

Viewed 319

Normally, when you create a block element, the element has a width of 100% by default. That rule still holds inside of a grid, unless you try to center the element using margin: auto. When centering a block element using margin: auto inside a grid the element shrinks to fit the contents. You can change this by explicitly setting the width to 100%. I have included a simple demo below.

.block {
  display: block;
  border: solid 3px green;
}

.grid {
  display: grid;
  border: solid 3px blue;
}

.content {
  border: solid 3px red;
  margin: 0.5rem auto;
  max-width: 30rem;
}
<div class="block">
  <div class="content">Some content in a block</div>
</div>
<div class="grid">
  <div class="content">Some content in a grid</div>
</div>

Can someone explain why it behaves this way?

2 Answers

From the specification:

By default, grid items stretch to fill their grid area. However, if justify-self or align-self compute to a value other than stretch or margins are auto, grid items will auto-size to fit their contents.

In grid and flex layouts, auto margins consume all available space in the specified direction.

For example, margin-top: auto means that all free space between the element and the top of the container will be consumed, shifting the element downward as much as possible.

From the question:

When centering a block element using margin: auto inside a grid the element shrinks to fit the contents.

The margins are consuming free space equally on all sides of the element. The only thing they can't consume is the content (not free space), leaving the content shrink-wrapped.

You can change this by explicitly setting the width to 100%.

The full row is now used space, not free space.


Related:

Related