CSS grid is the shortest way to center elements
- Published at
- Updated at
- Reading time
Today I was tweeting about a new CSS property I discovered:
It is a simple shorthand for – that's at least what I thought. It turns out that
place-items is a shorthand for
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 elements.
/* this class centers elements using flexbox
and is there to stay */
After sharing my disappointment, Benjamin mentioned something that I didn't think of before.
place-items works perfectly with
I have to admit that even when CSS
grid is cross-browser supported nowadays, I didn't use it much yet. It turns out that you can use
display: grid to center elements as quickly as when using flexbox.
display: grid on an element (see this CodePen as an example), pair the grid-declaration with
justify-items and you're good to go! You just centered the child of this element.
<span>hello from a centered span</span>
justify-items define the
justify-self properties on all direct grid children. Have a look at the devsheet below to learn about these CSS properties.
The nice thing about this approach; you can unify
justify-items into a single declaration –
There are only two CSS declarations needed to center elements using CSS
Well... there was.
place-items wasn't cross-browser supported when this article was published. You had to leverage PostCSS to use it. But browser support looks way better today! 🎉
You can read more about
place-items in the detailed MDN article about it.
Happy centering, and if you enjoyed this post don't forget to check out my other quick "Today I learned"-posts!