Swapnil Mane Profile picture
Tweets about coding, freelancing & SaaS ๐Ÿš€ Full-Stack Software Engineer at @GetGrabJobs & ๐Ÿ’š Top Rated freelancer at Upwork. ๐Ÿ“Š https://t.co/tdtSEwBMhs โšก https://t.co/At5CnqOfqj

Dec 5, 2021, 6 tweets

All the Ways to Center a Div in CSS! ๐Ÿ‘‡
Thread ๐Ÿงต

#CSS #Frontend #Javascript

โœ… For this, let's consider the following Image which is inside a div tag and the parent element of this div tag is the header tag.

So lets now look at all the ways we can center the div in CSS!๐Ÿ‘‡

1) Traditional Way:

For the parent element,
Set the position to 'relative' and height to '100vh'.

For the child element,
Set top, and left to '50%' and transform to 'translate(-50%,-50%)'

โญ And Done... Your Child Div is now set to Center!

2) Using Flexbox:
โœ… Just add the following properties to the parent element and the child div tag will get centered automatically!

height: 100vh;
display: flex;
justify-content: center;
align-items: center;

3) Using CSS Grid
โญ This is the Shortest and easiest way to center a div tag! โญ
Just add the following 3 lines to the parent element and the child div tag will get centered automatically!

height: 100vh;
display: grid;
place-items: center center;

Great, now you know all the ways to center a div tag.๐Ÿ˜Š
Let me know if you know any other ways to center a div tag down below ๐Ÿ‘‡ or let me know if you have any questions!

And if you liked the thread, then consider sharing... It means a lot to me! โค

Share this Scrolly Tale with your friends.

A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.

Keep scrolling