Centering in CSS has traditionally been a cause for frustration. Itâs an everyday task yet there are so many possible solutions! The approach you take will differ depending on whether youâre centering horizontally, vertically or both!
In this tutorial, weâll look at which methods are best in each scenario.
Horizontal Centering
Inline Elements
Inline elements like text (and links) are super simple to center horizontally using the text-align
property:
p {
text-align: center;
}
This works for inline, inline-block, inline-flex, inline-table, etc.
Block Elements
A block-level element can be centered if both its margin-left
and margin-right
properties are set to auto
(assuming the element has a width
). Itâs often done with the margin
shorthand:
.element {
margin: 0 auto;
}
However, the modern way to center block level elements (anything that isnât text) is to use Flexbox!
Letâs assume we have HTML like so:
<div class="container">
<div>.element</div>
</div>
Add the following CSS:
.container {
display: flex;
justify-content: center;
}
This will horizontally center any element inside the .container
element.
Vertical Centering
Vertical centering has traditionally been quite tricky. And more often than not itâd be accomplished with code like so:
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
This indeed works as it moves the child element back up half the distance of of its height. And it positions the middle of the child element at the middle of its parent.
However, we can do this much more simply with Flexbox:
.container {
display: flex;
align-items: center;
}
This will vertically center any element inside the .container
element.
Centering both Vertically and Horizontally
To center both vertically and horizontally we simply combine these techniques!
To perfectly center an element, in the middle of its container:
.container {
display: flex;
justify-content: center;
align-items: center;
}
If using CSS Grid, we can also do this easily:
.container {
display: grid;
place-items: center;
}
Anything can be centered in CSS!
Once you know the basics of Flexbox and Grid, youâll see just how simple it is! đ
Related Posts:
A little about me..
Hey, Iâm Tim! đ
Iâm a freelance business owner, web developer & author. I teach both new and experienced freelancers how to build a sustainable and successful freelancing business. Check out my Complete Guide to Freelancing if you'd like to find out more.
While you're here, you can browse through my blogs where I post freelancing tips, code tutorials, design inspiration, useful tools & resources, and much more! You can also join the newsletter, or find me on X.
Thanks for reading! đ