0 votes
1 view
in Web Technology by (14.7k points)

I have a div element which contains text, and I want to align the contents of this div vertically centre.

Here is my div style:

#box {

height: 170px;

width: 270px;

background: #000;

font-size: 48px;

color: #FFF;

text-align: center;

}

<div id="box"> Lorem ipsum dolor sit </div>

What is the best way to do this?

1 Answer

0 votes
by (33.1k points)

If you want to vertically centre text with CSS then use the below-mentioned CSS:-

div { 

height: 200px;

line-height: 200px;

text-align: center;

border: 2px dashed #f69c55;

}

span {

display: inline-block;

vertical-align: middle;

line-height: normal;

}

<div>

<span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Haec et tu ita posuisti, et verba vestra sunt. Non enim iam stirpis bonum quaeret, sed animalis. </span>

</div>

What CSS does here it is just size the <div>, vertically center aligns the <span> by setting the <div>'s line-height equal to its height, and makes the <span> an inline-block with vertical-align: middle. After these steps CSS sets the line-height back to normal for the <span>, so its contents will flow naturally inside the block.

...