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;
}
Number two:
This way is not supported by IE
.parent {
display: grid;
place-items: center;
}
Number three:
.parent {
position: relative;
}
.child {
position: absolute;
transform: translate(-50%,-50%);
left: 50%;
top: 50%;
}
Number four:
Mentioned by @mrdanielschwarz
.parent {
display: flex or grid;
height: 100vh;
}
.child {
margin: auto;
}
Which way you prefer and do you know other ways?
Top comments (18)
which one is more efficient to the web and can help me making responsive
if any suggestion pls reply
I recommend Flexbox, it's much easier.
Thank you sir
so, sir, it will help me in making the website responsive ??
Yeah of course it helps. Try this: w3schools.com/csS/css3_flexbox.asp
Flex and Grid both are great
thank you sir
margin: 0 auto;
Thanks Roy,
But it only works for centering items horizontally
Im recently loving grid because it gives you so much more control over responsive positioning.
Thanks Danial,
But it only works for centering items horizontally
sir, I tried this margin: auto and it centers the element
yes, Sir, it Works
Great! if you don't mind I add it to this post... is it ok?
Thanks for sharing!
My pleasure :)
I like No 3️⃣ 👍🏽
It's my pleasure :)