For many years the bane of any web designer's existence was something simple: centering an object on the page. Horizontally centering was one thing, but getting an item to vertically center was a whole different monster. Even worse was both vertically and horizontally centering an element. However, modern CSS stylings have made this a snap with just a few lines of code. Gone are the days of absolute positioning an element 50% of the top and left of its container and bumping it back negative 50% with a transform. Now we can use Flexbox or CSS Grid to quickly center the element and move on.
Using Flexbox
Flexbox makes it very easy to align items in the center of the container with just three lines of CSS. Just set the display to flex
and center the items horizontally (justify-content: center
) and vertically (align-items: center
).
css
.container {
display: flex;
justify-content: center;
align-items: center;
}
Now all items originate from the center of the container!
It is important to note that if you change to flex-direction: column
the properties have the opposite effect: justify-content
becomes the vertical axis and align-items
becomes the horizontal. Think of it as rotating the container element's axes.
Using CSS Grid
Meanwhile, CSS Grid makes it even easier by only needing place-items: center
to center elements in the grid. Just set the display to grid
, place the items, and you're off to the races.
css
.container {
display: grid;
place-items: center;
}
If you want to control the individual axes you can use the same properties as we did with Flexbox instead, justify-content
for the horizontal axis and align-items
for the vertical.
css
.container {
display: grid;
justify-content: center;
align-items: center;
}
Never get tripped up with centering an element on your website again. Whether you are using Flexbox or CSS Grid add a couple lines of code and move on to something more deserving of your skill and attention.
Credit
Today’s Tuesday Tips was adapted from a series of posts on Daily Dev Tips.