DEV Community

Cover image for Best ways to center objects in CSS (Horizontally and Vertically )
Amir Jafari
Amir Jafari

Posted on • Updated on

Best ways to center objects in CSS (Horizontally and Vertically )

In this article, I'm going to show you how you can center your objects horizontally and vertically in CSS in three different ways.

Number one:

.parent {
  display: flex;
  align-items: center;
  justify-content: center;
}
Enter fullscreen mode Exit fullscreen mode

Number two:

This way is not supported by IE

.parent {
  display: grid;
  place-items: center;
}
Enter fullscreen mode Exit fullscreen mode

Number three:

.parent {
  position: relative;
}
.child {
  position: absolute;
  transform: translate(-50%,-50%);
  left: 50%;
  top: 50%;
}
Enter fullscreen mode Exit fullscreen mode

Number four:

Mentioned by @mrdanielschwarz

.parent {
  display: flex or grid;
  height: 100vh;
}
.child {
  margin: auto;
}
Enter fullscreen mode Exit fullscreen mode

Which way you prefer and do you know other ways?

Top comments (21)

Collapse
 
amankanojiya profile image
AMANKANOJIYA

which one is more efficient to the web and can help me making responsive
if any suggestion pls reply

Collapse
 
aoussiadmehdi profile image
Mehdi Aoussiad

I recommend Flexbox, it's much easier.

Collapse
 
amankanojiya profile image
AMANKANOJIYA

Thank you sir

Collapse
 
amankanojiya profile image
AMANKANOJIYA

so, sir, it will help me in making the website responsive ??

Thread Thread
 
aoussiadmehdi profile image
Mehdi Aoussiad

Yeah of course it helps. Try this: w3schools.com/csS/css3_flexbox.asp

Collapse
 
amirjafari1992 profile image
Amir Jafari

Flex and Grid both are great

Collapse
 
amankanojiya profile image
AMANKANOJIYA

thank you sir

Collapse
 
veslav3 profile image
Roy Honders

margin: 0 auto;

Collapse
 
amirjafari1992 profile image
Amir Jafari

Thanks Roy,
But it only works for centering items horizontally

Collapse
 
zeked profile image
Zeke-D

Im recently loving grid because it gives you so much more control over responsive positioning.

Collapse
 
amirjafari1992 profile image
Amir Jafari

Thanks Danial,
But it only works for centering items horizontally

Collapse
 
amankanojiya profile image
AMANKANOJIYA

sir, I tried this margin: auto and it centers the element

Collapse
 
leenairen profile image
Leena Iren

Thanks for sharing!

Collapse
 
amirjafari1992 profile image
Amir Jafari

My pleasure :)

Collapse
 
amankanojiya profile image
AMANKANOJIYA

yes, Sir, it Works

Collapse
 
tahmash profile image
Tahmas

I like No 3️⃣ 👍🏽

 
amirjafari1992 profile image
Amir Jafari

Great! if you don't mind I add it to this post... is it ok?

Collapse
 
amirjafari1992 profile image
Amir Jafari

It's my pleasure :)