Search code examples
htmlcsscss-gridcentering

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


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?


Solution

  • 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.