Signup/Sign In
PUBLISHED ON: AUGUST 24, 2021

How to align text vertically center in a DIV element using CSS?

Answer: Using CSS vertical-align and line-height property.

In HTML, the element can be aligned using CSS. There are several properties of alignment in CSS. One among them is aligning the text vertically center in a Div element.

In this tutorial, we will be learning the ways to align the text vertically center using CSS.

Using vertical-align Property

The CSS vertical-align property can be used to vertically center the text within the div element. Also, we need to add display: table/ display: table-cell along with it to vertically center the element relative to its parent element.

You can set height and width and border to the parent element.

Example: Vertically align the text using the vertical-align Property

In this program, we have used vertical-align: middle to align the text vertically to the center of the parent element.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
<style>
      div {
        display: table-cell;
        width: 250px;
        height: 200px;
        padding: 10px;
        border: 5px solid blue;
        vertical-align: middle;
      }
    </style>
  </head>
  <body>
    <div>Vertically center align text within div element</div>
  </body>
</html>

Output

Here is the output of the above program.

text vertically centered aligned

Using line-height property

The line-height property can be used to vertically center the text in div. Just add the line- height equal to the height of the div element.

It will add equal spaces to the top and bottom of the div element which will vertically center the text.

Example: Vertically center align text using line-height

Here the value of line- height and height is the same for the div element. Further, we have added some other properties like width, border and text-align to the div element.

Using Flexbox property

The flexbox property can also be used to vertically center align the text within the div element. Use justify-content:center to align and align-items:center to the div element.

Example: Vertically center align text using flexbox property

In addition to justify-content and align-items, we have used display: flex, height, width, and border property in the code.

Using CSS transform property

The transform property along with position can also align the div contents vertically centered. Use position: relative to the parent element and position: absolute to the child element.

Example: Vertically center text using the transform property

In this example, transform: translate(-50%, -50%) is used to move the text 50% up and 50% left to center it vertically.

Conclusion

There are several ways to vertically center align the text within the div element using CSS. You have explained some ways with examples for this. You can choose any way to vertically center the text.



About the author: