DEV Community

Cover image for 3 Ways to CENTER a div in CSS

3 Ways to CENTER a div in CSS

Code Oz on November 24, 2021

3 ways to center a div in HTML/CSS!! With Position /* Using positions */ .parent { position: relative; } .child { left: 50%...
Collapse
 
unclecheap profile image
UncleCHEAP • • Edited

Let's not forget yet a 4th way. No need for "positioning."

.parent {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.child {
    display: inline-block;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
codeoz profile image
Code Oz •

Didn't know it! Thanks you for sharing it!

Collapse
 
undqurek profile image
undqurek • • Edited

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...

Collapse
 
codeoz profile image
Code Oz •

very nice sharing thanks!

Collapse
 
bias profile image
Tobias Nickel •

good post,

your last example for the grid example, still uses the flex class container-flexbox in the html

Collapse
 
codeoz profile image
Code Oz •

thank you bro

Collapse
 
thanhrossi profile image
Tran Thanh •
Collapse
 
ezraguy profile image
Guy •

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

Collapse
 
codeoz profile image
Code Oz •

nice! I remove it from code thanks!

Collapse
 
yevgeniyadanila profile image
Yevgeniya Danila •

i am learning CSS, thank you for the article

Collapse
 
codeoz profile image
Code Oz •

happy to help you :)

Collapse
 
shadowruge profile image
izaias •

wonderful, simple and straightforward

Collapse
 
codeoz profile image
Code Oz •

thank you a lot Izaias

Collapse
 
captflys profile image
CaptFlys •

Nice!

Collapse
 
latze profile image
latze •

Hey thanks for this!

But you can Also just center a div with a text-align: center;

Collapse
 
unclecheap profile image
UncleCHEAP •

Left-to-right center yeah, but that doesn't affect the relation to its parent vertically.

Collapse
 
codeoz profile image
Code Oz •

Totally agree!