Modern Way to Center Elements with CSS
If you’ve worked with CSS for a longer period, you’ve probably seen and used about a dozen different ways to center block-level elements on the page. These methods used to vary between a combination of negative margins, CSS translations, Flexbox, and more. Heck, I’ve even used the infamous display: table
back in the day.
Fortunately, we today have a solution that requires only two lines of CSS, display: grid
and place-self: center
. The following code snippet will position any item in the middle of the container both vertically and horizontally:
.container { display: grid }
.center {
/* Place this item in the middle of the container
* both vertically and horizontally. */
place-self: center;
}
You can also use place-content
on the container itself to center all child items in the middle both vertically and horizontally:
.container {
display: grid;
/* Place all items in the container in the middle
* both vertically and horizontally. */
place-content: center;
}
In case you want to stack these items, you can utilize another simple property, grid-area
:
.container { display: grid }
.center {
/* Place this item in the middle of the container
* both vertically and horizontally. */
place-self: center;
/* Stack all items on the same grid area. */
grid-area: 1/1;
}
I hope you find this useful! I first learned about the above method for stacking with grid-area
from Ana Tudor. Here’s also a quick Codepen to demonstrate the modern way to center elements with CSS:
See the Pen Untitled by Ariel Salminen (@arielsalminen) on CodePen.