CSS grid will soon be the shortest way to center elements

This post is part of my Today I learned series in which I share all my learnings regarding web development.

Today I was tweeting about a new CSS property I discovered: place-items . It is a simple shorthand for align-items and justify-content – that'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.

.center { display : flex ; align-items : center ; justify-content : center ; }

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 ; }

# 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!