Home > Article > Web Front-end > Five methods to achieve vertical centering of content in divs
If there is only one line or a few words to be vertically centered, then it is the simplest to make, just let the text The line height is the same as the height of the container, for example:
p { height:30px; line-height:30px; width:100px; overflow:hidden; }
This code can achieve the effect of centering the text vertically in the paragraph.
Another method is very similar to the line height method. It is also suitable for one or several lines of text to be vertically centered. The principle is to use padding to vertically center the content. Centered, for example:
p { padding:20px 0; }
The effect of this code is similar to the line-height method.
Set the container to display:table, then set the child element, that is, the element to be displayed vertically in the center, to display:table-cell, and then add vertical- align:middle to achieve.
The html structure is as follows:
<p id="wrapper"> <p id="cell"> <p>测试垂直居中效果测试垂直居中效果</p> <p>测试垂直居中效果测试垂直居中效果</p> </p></p>
css code:
#wrapper {display:table;width:300px;height:300px;background:#000;margin:0 auto;color:red;}#cell{display:table-cell; vertical-align:middle;}
Unfortunately, IE7 and below are not supported.
css code is as follows:
.center-vertical{ position: relative; top:50%; transform:translateY(-50%); }.center-horizontal{ position: relative; left:50%; transform:translateX(-50%); }
html code:
<p class="center"> <p class="text"> <p>我是多行文字</p> <p>我是多行文字</p> <p>我是多行文字</p> </p></p>
css code:
.center { width: 300px; height: 200px; padding: 10px; border: 1px solid #ccc; background:#000; color:#fff; margin: 20px auto; display: -webkit-box; -webkit-box-orient: horizontal; -webkit-box-pack: center; -webkit-box-align: center; display: -moz-box; -moz-box-orient: horizontal; -moz-box-pack: center; -moz-box-align: center; display: -o-box; -o-box-orient: horizontal; -o-box-pack: center; -o-box-align: center; display: -ms-box; -ms-box-orient: horizontal; -ms-box-pack: center; -ms-box-align: center; display: box; box-orient: horizontal; box-pack: center; box-align: center; }
The above is the detailed content of Five methods to achieve vertical centering of content in divs. For more information, please follow other related articles on the PHP Chinese website!