Skip to content
GreenSnippets

Center anything with grid

Center an element horizontally and vertically using two lines of CSS.

CSS
.center {
  display: grid;
  place-items: center;
  min-height: 100dvh;
}

Example / expected output

Output
<!-- <div class="center"><div>I'm centered</div></div> -->

How it works

place-items: center is shorthand for align-items and justify-items. Combined with display: grid it centers children in both axes. Use place-content: center instead if the child should size to its content rather than stretch.

This snippet has been reviewed but was not executed by an automated test. Test it in your own environment before relying on it.