/

How to Center an Element with CSS

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
2
3
p {
text-align: center;
}

Blocks

For non-text elements, the preferred way to center them horizontally is by using Flexbox:

1
2
3
4
#mysection {
display: flex;
justify-content: center;
}

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
2
3
4
section {
margin: 0 auto;
width: 50%;
}

The margin: 0 auto; shorthand is equivalent to:

1
2
3
4
5
6
section {
margin-top: 0;
margin-bottom: 0;
margin-left: auto;
margin-right: auto;
}

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
2
3
4
#mysection {
display: flex;
align-items: center;
}

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
2
3
4
5
#mysection {
display: flex;
align-items: center;
justify-content: center;
}

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
2
3
4
5
body {
display: grid;
place-items: center;
height: 100vh;
}

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”]