parm530
11/9/2017 - 9:42 PM

Vertical Alignment

Techniques for vertically aligning text or elements

Line Height Method

  • Vertically aligning a single line of text:
    • Set the line-height of the element containing the text larger than its font-size
    • Default: Equal space will be given above and below the text so it will sit vertically in center
<div id="parent">
  <div id="child">Text here</div>
</div>
#child {
  line-height: 200px; // Value is arbitrary, could be anything
}

What if the element was an image and not text?

  • The code above can be used, however add 1 more line of code:
<div id="parent">
  <img src="image.png" alt="" />
</div>
#parent {
  line-height: 200px;
}

#parent img {
  vertical-align: middle;
}
  • You'll again need to set the line height greater than the height of the image!

Using CSS Table Method

  • CSS tables are different than HTML tables!!

Vertical Align

  • Use with elments whose display is inline or inline-block
  • Make sure to use on its parent!!
<div class="parent">
  <div class="child">
  </div>
</div>
.parent {
  text-align: middle;
}

.child {
  display: inline-block;
}