This content originally appeared on DEV Community and was authored by Ethan
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.
Text-Align Approach
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 children element to display: inline-block
.
Pretty self-explanatory, you might say.
The (Classic) Absolute Approach
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 to the other direction, 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.
Flexbox Approach
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.
The (Two-Lined) Grid Approach
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.
.wrapper {
display: grid;
place-items: center;
}
See? That’s even shorter.
I hope you’ve found this short post informative and helpful, and I’d love to hear your thoughts about it. Thanks for reading!
Sources
- Codegrid. (2020, April 3). How to center text horizontally and vertically in CSS. Medium. (https://medium.com/@codegridweb/how-to-center-text-horizontally-and-vertically-in-css-67e24ceb573f)
- Fireship. (2021). Top 3 ways to center a DIV with CSS [YouTube Shorts]. In YouTube. (https://www.youtube.com/watch?v=njdJeu95p6s)
- Sun, S. (2020, August 3). Center CSS with style: A how-to. Medium; Better Programming. (https://betterprogramming.pub/how-to-center-things-with-style-in-css-dc87b7542689 )
Originally posted on Medium on June 17, 2021.
This content originally appeared on DEV Community and was authored by Ethan
Ethan | Sciencx (2022-01-31T03:56:53+00:00) How to Center Elements with CSS. Retrieved from https://www.scien.cx/2022/01/31/how-to-center-elements-with-css/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.