Vertical Align Middle

Vertical Align Middle is a difficult task?

When we develop web pages, we will have to align the text of div in the middle either horizontally or vertically. Horizontal centering is easy, if we use the text-align: center for the parent element. But usually centering the text vertically is a trouble for the developers. If the content is only one line, then we can use line-height property to set the content vertically aligned in the middle of the container. By setting the line-height of the text to be equal to the height of the container. But when there are multiple lines of text? Trapped? How we will align it in the middle of the container?

Vertical Align Middle

We will see different methods for centering or vertically aligning the text in the middle of a container.

Vertical Align with line-height method

Vertical Align Middle-line-height
As a first step, we will add a container and text to be aligned in the middle of the container.

Html for Vertical Align with line-height method

<div class="demo1">
This is sample text. This is sample text. This is sample text.
</div>

CSS for Vertical Align with line-height method

.demo1 {
    line-height: 100px;
    height: 100px;
}

Here we will give the line-height: 100px, as the height of the container is 100px. Now the text will be aligned in the middle of the div. But, if one more line is added, then this method will not work. First line will be in the middle and the line height between the two lines will be 100px. So we have to use a different method to align the text in the middle of the div, when there are multiple lines.

Demo for vertical align middle with line-height

Vertical Align Middle

Vertical align middle with table method

Vertical align Middle-table-method

Vertical align middle with table method is very useful when the text is more than one line. Let us see how to do this.

Html Vertical align middle with table method

<div class="demo2">
     This is sample text. This is sample text. This is sample text. This is sample text. This is sample text. This is sample text. This is sample text. This is sample text. This is sample text.
</div>

CSS for Vertical align middle with table method

.demo2 {
	display: table-cell;
	vertical-align: middle;
	line-height: 20px;
	height: 150px;
	text-align: justify;
    }

Demo for Vertical align middle with table method

Vertical Align Middle

label, , , , , , , , ,

About the author