You are a professional developer if you can center a div, text or image horizontally and vertically!
I'm sure you've heard developer jokes about this more than once at your work, on Twitter and surely on LinkedIn 😂 — It's also probably the most searched for trick on stackoverflow.com, and well, in this tutorial you'll see that it's quite simple to do when you know how.
Center a div with Float CSS
The first approach is old fashion CSS also known as Float CSS, In supported browsers (most of them), you can use top: 50%
/left: 50%
in combination with translateX(-50%) translateY(-50%)
to dynamically vertically/horizontally center the element.
Center a div with Flex CSS
The second approach is by using a more modern technique, well known as Flexbox CSS, In supported browsers, set the display
of the targeted element to flex
and use align-items: center
for vertical centering and justify-content: center
for horizontal centering. Remember, the parent container will also need height (in this case, 300px).
Center a div with Grid CSS
The last one, and the most simple is by using Grid CSS (The modern and most recommend way of using CSS), set the display
of the targeted element to grid
and use on the child element align-self: center
for vertical centering and justify-self: center
for horizontal centering.
I hope you enjoyed reading this and I'm curious to hear if this tutorial helped you.
Please let me know your thoughts in the comments section below.
Also, you can connect with me on LinkedIn or Twitter.
Talk soon
Wrapping
In this short tutorial, you have learned how to center a div, text or any HTML element with 3 simple but powerful CSS techniques :
- Float
- Flexbox
- Grid
Get more techniques and resources here.