First, row height (line-height) method
If you want to vertically center only one line or a few words, it is the most simple to make, as long as the line height of the text and the container is the same height, such as:
p {height:30px; line-height:30px; width:100px; overflow:hidden;}
This code allows the text to be centered vertically in the paragraph.
Second, the internal margin (padding) method
The other approach is similar to the line height method, which is also suitable for vertical centering of one or several lines of text, using padding to center content vertically, such as:
p {padding:20px 0;}
This code has the same effect as the Line-height method.
Three, the simulation table method
Set the container to Display:table, and then set the child element, which is the element that you want to center vertically, to Display:table-cell, and then add vertical-align:middle to implement it.
The HTML structure is as follows:
<p id= "wrapper" > <p id= "cell" > <p> Test Vertical Center effect test vertical Center effect </p> <p> Test vertical Center Effect test vertical Center effect </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 the following are not supported.
Four, CSS3 of the transform to achieve
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: CSS3 The Box method to achieve horizontal vertical centering
HTML code:
<p class= "center" > <p class= "text" > <p> I am multiline text </p> <p> I am multiline text </p> <p> I am multiline text </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;}