Harish Harish - 1 month ago 21
CSS Question

Vertical alignment in css responsive

This question might be an answered one and it may sound silly. I would like to align any element whether it is a text, image or a div to align in the center vertically and it should also work in responsive screens. I did try it by adding margin-top with manual percentages. I would like to know if there is a simple and best way to make the vertical alignment responsive.

I even did some research in google about it, some of them suggested to change the display property of the container to table and the div to table cell and then use the vertical alignment as middle. This sounds simple but it also effects the other elements in the page which I don't want to be as a table. Hence I'm looking for best alternate option. Please help. Thank you in advance :)



.in-middle{
width:100%;
margin-top: 25%;
}

<body>
<div class="in-middle">
<h1>This should be aligned in the center</h1>
<p>Paragraph which should also be centered</p>
</div>
</body>




Answer

Use the following solution using the tranform property:

.in-middle{
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
<body>
  <div class="in-middle">
    <h1>This should be aligned in the center</h1>
    <p>Paragraph which should also be centered</p>
  </div>
</body>