The most challenging thing for a web developer to do is to center a div
horizontally and vertically. Centering elements are common in web development, and there are tons of ways to get the job done.
Here are some ways to center any element using CSS.
The most common way of centering is to align the text to the center. In other words, set the parent element to text-align: center
and the child element to display: inline-block
.
.wrapper {
text-align: center;
}
.wrapper .block {
display: inline-block;
}
Pretty self-explanatory, you might say.
A classic way of centering elements is to set the parent element to absolute (or fixed) and set the top
and left
properties by 50%. To move the element back, you translate the x-axis and y-axis by -50% with the transform
property.
Here’s what the final code should look like:
.wrapper {
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%, -50%);
}
This perplexing hack was the gold standard before. But in 2009, CSS introduced Flexbox, and that’s what we’re going to talk about next.
In this approach, we set the parent element into a flexible column or row, then align and justify the children to the center using align-items
and justify-content
. One thing to note: align-items
is for vertical centering and justify-content
is for horizontal centering.
.wrapper {
display: flex;
align-items: center;
justify-content: center;
}
But what if we can center the div block with less code? That’s where the grid comes in, and it’s shorter than you think.
Here’s a shorter way to center elements. Define the parent element as a grid and tell it to place the items inside to center
. This is even shorter than other approaches.
.wrapper {
display: grid;
place-content: center;
}
See, told ya.