How to make text center align in div?

You may think it is easy to center text in div:

tml>
<head>

</head>
<body> 
<div style="background-color:red;width:100px;height:100px;text-align:center;">
subscribe
</div>
</body>
</html>

In the above example, you want to use the css property “text-align:center” to make text appear in center of div. The actual result is:

The “text-align:center” property only makes text center in div horizontally. How to center text in div vertically? You may think about using the “vertical-align: middle;” css property instead of the “text-align:center;” property. Unfortunately, this property cannot align the text vertically middle in div, and it cannot even center the text horizontally as the “text-align:center;” property.

There are two methods to make text aligned vertically in div:

use the line-height property and set the value of the property equal to the height of the div.

<html>
<head>

</head>
<body> 
<div style="background-color:red;width:100px;height:100px;line-height:100px;">
subscribe
</div>
</body>
</html>

Note that the line-height property does not change the height of the contained text. If the line-height is greater than the font-size(the actual height of the text), the difference(leading) is cut in half and distributed evenly on the top and bottom of the text, resulting in the text vertically centered in the div.

Use the “display:table;” and “display:table-cell” css property.

Now you need two elements with parent/child relationship. You apply “display:table;” to the parent div and apply both “display:table-cell” and “vertical-align: middle;” to the child div. The text in the child div will be displayed in the middle of it.

<html>
<head>

</head>
<body> 
<div style="background-color:red;width:100px;height:100px;display:table;">
<div style="display:table-cell;vertical-align: middle;">Subscribe</div>
</div>
</body>
</html>

The result is shown as:

The “display: table;” can be replaced by “display: inline-table;”. Both produce the same result.

Combined with “text-align:center;”(regardless it is applied to parent div or child div), the text is now aligned both vertically and horizontally in the div.

<html>
<head>

</head>
<body> 
<div style="background-color:red;width:100px;height:100px;display:table;">
<div style="display:table-cell;vertical-align: middle;text-align:center;">Subscribe</div>
</div>
</body>
</html>

The final display result:

If you like my content, please consider buying me a coffee. Buy me a coffeeBuy me a coffee Thank you for your support!

Leave a Reply