Center a div vertically and horizontally
CSS

Center a div vertically and horizontally

Center a div vertically and horizontally

Hi, let’s center a div vertically and horizontally.

However, it doesn’t matter you want to center a div or an image or any other element. This CSS technique is the same for all elements. I am sharing two methods to do this task. Try the given examples but I would suggest you use method 2 which is very easy.

Method 1:

CSS:

.main-container{width: 100%; height: 500px;}
.inner-container{width: 100px; height: 150px; margin: auto; position: relative; top: 50%; transform: translateY(-50%);}
.border{border: 1px solid #333;}

HTML:

<div class="main-container border">
<div class="inner-container border">
<h1>नमस्ते !</h1>
</div>
</div>

Method 2:

The second and easy method to achieve the same thing is use display:flex;

You need to set display:flex; for the parent div and then use justify-content: center; to center it’s child horizontally and use align-items: center; to center it’s child vertically. You need to write these two properties only for parent div.

Thanks for visiting.

Author

I am a Full Stack Web Developer. I have more than 8 years of experience in the web design and development industry.

Leave a Reply

Your email address will not be published. Required fields are marked *