Five methods for vertical center of content in div, five methods for vertical center of div
Reposted blog: http://www.cnblogs.com/moqiutao/p/4807792.html
I. line-height Method
If only one or several lines of text are vertically centered, it is the easiest to create, as long as the line height of the text is the same as the height of the container. For example:
p { height:30px; line-height:30px; width:100px; overflow:hidden; }
This code can align the text vertically in a paragraph.
Ii. padding method
Another method is similar to the line height method. It is also suitable for vertical center of one or several lines of text. The principle is to use padding to vertically center the content, for example:
p { padding:20px 0; }
This code is similar to the line-height method.
Iii. Table Simulation
Set the container to display: table, set the sub-element, that is, the element to be vertically centered to display as display: table-cell, and add vertical-align: middle.
The html structure is as follows:
<Div id = "wrapper"> <div id = "cell"> <p> test vertical center Effect Test vertical center effect </p> <p> test vertical center Effect Test vertical center Effect center effect </p> </div>
Css code:
#wrapper {display:table;width:300px;height:300px;background:#000;margin:0 auto;color:red;}#cell{display:table-cell; vertical-align:middle;}
Implementation:
Unfortunately, IE7 and below are not supported.
IV. Implementation of CSS3 transform
The css code is as follows:
.center-vertical{ position: relative; top:50%; transform:translateY(-50%);}.center-horizontal{ position: relative; left:50%; transform:translateX(-50%); }
V. The box method of css3 achieves horizontal and vertical center
Html code:
<Div class = "center"> <div class = "text"> <p> I am a multiline text </p> <p> I am a multiline text </p> </div>
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;}
Result