DEV Community


TIL: CSS grid will soon be the shortest way to center elements

stefanjudis profile image Stefan Judis Originally published at on ・2 min read

Today I was tweeting about a new CSS property I discovered: place-items. It is a simple shorthand for align-items and justify-contentthat's at least what I thought. It turns out that it's shorthand for align-items and justify-items (thanks Benjamin for pointing that out).

This discovery made me sad initially because it meant that I could not get rid of one CSS declaration in my Flexbox based classes to center things.

/* this class is there to stay */
.center {
  display: flex;
  align-items: center;
  justify-content: center;
Enter fullscreen mode Exit fullscreen mode

After sharing my disappointment, Benjamin mentioned something that I didn't think of before. place-items works perfectly with display: grid.

I have to admit that even when CSS grid is cross-browser supported nowadays , I didn't use it that much, but it turns out that you can use it to center things easily by defining it on an element with only one row and only one column (see this CodePen as an example).

.center-using-grid {
  display: grid;
  align-items: center;
  justify-items: center;

.center-using-grid-even-shorter {
  display: grid;
  place-items: center;
Enter fullscreen mode Exit fullscreen mode

Sounds too good to be true? Is there a catch?

Well... kind of. place-items is not cross-browser supported yet (basically it's Chrome and Firefox today), but fortunately, PostCSS has you covered so that you can use it today. 🎉

You can read more about place-items in the detailed MDN article about it.

Happy centering!

Discussion (0)

Editor guide