3

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?

digby280
  • 879
  • 1
  • 7
  • 22
  • 1
    Because in grid/flexbox the margin:auto pushes the element from those respective sides to shrink it down to it's content size. That's the default behaviour. Grid/flex child is not `display:block` regardless of it's default display type. – Paulie_D Jun 11 '20 at 14:50

2 Answers2

3

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.

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
1

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:

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701