CSS Text Vertical Align Middle in Div

When we create a website template or some design in HTML, we need to align some elements vertically center inside the box sometimes. This could be aligning text middle inside div or some image needs to be vertically aligned in the center.

There are many ways to vertically align HTML elements using some CSS style. Here, we will provide a list of popular CSS methods to middle text vertically within div.


1) CSS Vertical align div text using flexbox (Best)

The best way to align text vertically in a div is by using CSS flex property. You need to use flexbox along with align-items: center for child.

HTML Code

<div>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vitae sapien ipsum. Mauris faucibus odio id orci aliquam, a varius elit mollis. Praesent rutrum, risus quis tempus dictum, nulla ex fermentum eros, eu luctus nisi neque eu tellus.
</div>

CSS Code:

div {
  display: flex;
  justify-content: center; /* align horizontal */
  align-items: center; /* align vertical */
  border: 2px solid grey;
  min-height: 200px;
  padding: 20px;
}

Try & Run Code: https://codepen.io/tutorialsclass/pen/MWKyONg


2) CSS Vertical align div text using table-cell and vertical-align:

You can align text vertically by setting display: table; on outer tag and display: table-cell on inner tag.

HTML Code

<div>
<span>
    <div>
  <span>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vitae sapien ipsum. Mauris faucibus odio id orci aliquam, a varius elit mollis. Praesent rutrum, risus quis tempus dictum, nulla ex fermentum eros, eu luctus nisi neque eu tellus.
  </span>
</div>
</span>
</div>

CSS Code:

div {
  display: table;
  height: 100px;
  width: 100%;
  text-align: center;
  border: 2px solid grey;
}
span {
  display: table-cell;
  vertical-align: middle;
  padding: 10px;
}

Try & Run Code: https://codepen.io/tutorialsclass/pen/GRoZWyw


3) CSS Vertical align div single line text using line-height & vertical-align

This method is useful when you have single-line text to vertically align. You need to set the same line-height, height, and vertical-align in CSS.

HTML Code

<div>
<span>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</span>
</div>

CSS Code:

div {
    height: 120px;
    line-height: 120px;
    text-align: center;
    border: 2px solid grey;
}
span {
    display: inline-block;
    vertical-align: middle;
    line-height: normal;
}

Try & Run Code: https://codepen.io/tutorialsclass/pen/vYLGgPe


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.