Harish
Harish

Reputation: 1273

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>

Upvotes: 4

Views: 27655

Answers (4)

Sebastian Brosch
Sebastian Brosch

Reputation: 43574

You can use the following solution, using the tranform property:

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

It's not recommended to use margin-top instead of tranform to vertically center elements.

Upvotes: 15

Mohammad Usman
Mohammad Usman

Reputation: 39322

You should use css3 flexbox. It will center your content vertically and horizontally and it won't overlap over the content following it.

body {
  margin: 0;
}
.in-middle {
  flex-direction: column;
  justify-content: center;
  align-items: center;
  display: flex;
  height: 100vh;
}
<body>
  <div class="in-middle">
    <h1>This should be aligned in the center</h1>
    <p>Paragraph which should also be centered</p>
  </div>
  <p>Lorem ipsum dolor sit amet, Lorem ipsum dolor sit amet, Lorem ipsum dolor sit amet,Lorem ipsum dolor sit amet, Lorem ipsum dolor sit amet,Lorem ipsum dolor sit amet, Lorem ipsum dolor sit amet...</p>
</body>

Upvotes: 10

Alex
Alex

Reputation: 471

With flexbox:

.in-middle {
  height: 100%;      
  display: flex;
  align-items: center;
}

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

Upvotes: 2

Ron.Basco
Ron.Basco

Reputation: 2438

position: absolute;
   top: 50%;
   transform: translateY(-50%);

this will center the element vertically.

.in-middle{
   width:100%;
   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>

Upvotes: 2

Related Questions