3 ways to center a div in HTML/CSS!!
With Position
/* Using positions */
.parent {
position: relative;
}
.child {
left: 50%;
position: absolute;
top: 50%;
transform: translate(-50%, -50%);
}
<div
class="parent"
style="background: blue; width: 500px; height: 250px;"
>
<div
class="child"
style="color: white;"
>
I'm center
</div>
</div>
With Flexbox
/* Using flexbox */
.container-flexbox {
align-items: center;
display: flex;
justify-content: center;
}
<div
class="container-flexbox"
style="background: green; width: 500px; height: 250px;"
>
<div
style="color: white;"
>
I'm center
</div>
</div>
With Grid
/* Using Grid */
.container-grid {
display: grid;
place-content: center;
}
<div
class="container-flexbox"
style="background: orange; width: 500px; height: 250px;"
>
<div
style="color: white;"
>
I'm center
</div>
</div>
I hope you like this reading!
🎁 You can get my new book Underrated skills in javascript, make the difference
for FREE if you follow me on Twitter and send message to me 😁 and SAVE 19$ 💵💵
Or get it HERE
🇫🇷🥖 For french developper you can check my YoutubeChannel
☕️ You can SUPPORT MY WORKS 🙏
🏃♂️ You can follow me on 👇
🕊 Twitter : https://twitter.com/code__oz
👨💻 Github: https://github.com/Code-Oz
And you can mark 🔖 this article!
Top comments (17)
Let's not forget yet a 4th way. No need for "positioning."
Didn't know it! Thanks you for sharing it!
Good job!
Some additional solutions:
dirask.com/posts/CSS-center-child-...
dirask.com/posts/CSS-center-child-...
And as last one, composition of 10 approaches (I like it mostly):
dirask.com/posts/CSS-center-elemen...
very nice sharing thanks!
good post,
your last example for the grid example, still uses the flex class
container-flexbox
in the htmlthank you bro
Nice post!
If I can add one thing is that in the second solution the
flex-direction: column is not really needed to center the div
nice! I remove it from code thanks!
Nice!
wonderful, simple and straightforward
thank you a lot Izaias
i am learning CSS, thank you for the article
happy to help you :)
css-tricks.com/centering-css-compl...
Hey thanks for this!
But you can Also just center a div with a text-align: center;
Left-to-right center yeah, but that doesn't affect the relation to its parent vertically.
Totally agree!