How to Center an Element with CSS
Centering an element with CSS can sometimes be tricky, but with modern CSS techniques, it has become much easier. In this blog post, I will guide you through the different ways to center elements using CSS, both horizontally and vertically.
Center Horizontally
Text
To center text horizontally, simply set the text-align
property to center
:
1 | p { |
Blocks
For non-text elements, the preferred way to center them horizontally is by using Flexbox:
1 | #mysection { |
This will center any element inside #mysection
horizontally.
[image: flexbox-horizontal-center.png]
Alternatively, if you prefer not to use Flexbox, you can center non-text elements by applying an automatic margin to the left and right, and setting the width of the element:
1 | section { |
The margin: 0 auto;
shorthand is equivalent to:
1 | section { |
Just remember to set the item to display: block
if it’s an inline element.
Center Vertically
Centering an element vertically has traditionally been more challenging. However, with Flexbox, it has become much simpler:
1 | #mysection { |
This will vertically center any element inside #mysection
.
[image: flexbox-vertical-center.png]
Center Both Vertically and Horizontally
You can combine Flexbox techniques to center an element both vertically and horizontally:
1 | #mysection { |
This will completely center an element in the page, both vertically and horizontally.
[image: flexbox-center.png]
You can achieve the same result using CSS Grid:
1 | body { |
I hope this guide has helped you understand how to center elements with CSS. With modern techniques like Flexbox and CSS Grid, centering elements has become much more accessible. Give them a try and see how they can simplify your CSS centering needs.
tags: [“CSS centering”, “CSS Flexbox”, “CSS Grid”]