It is relatively simple to use CSS to horizontally center elements. Row-level elements can set the text-align center of their parent elements, and block-level elements can set their left and right margins to auto. This article collects six methods for vertical center of elements using CSS. Each method is applicable to different situations and can be selected in actual use.
I,
Line-height Method
It is applicable to setting the vertical center of a single line of text in a row height,
<div id="parent"><div id="child">Text here</div></div><style> #child {line-height: 200px;}</style>
If the code for a vertical image is as follows:
<div id="parent"></div>#parent {line-height: 200px;}#parent img {vertical-align: middle;}
Ii. Table-Cell Method
The Code is as follows:
<Div id = "parent"> <Div id = "child"> content here </div> <style> # parent {display: Table ;} # child {display: Table-cell; Vertical-align: middle ;}</style> <! -- CSS should be applied for IE8 or earlier --> <style ># child {display: inline-block;} </style>
Iii. Absolute positioning and negative margin for block-level elements
The Code is as follows:
<div id="parent"><div id="child">Content here</div></div><style> #parent {position: relative;} #child { position: absolute; top: 50%; left: 50%; height: 30%; width: 50%; margin: -15% 0 0 -25%; }</style>
4. Absolute positioning and stretching are common, but cannot work normally when IE version is earlier than 7
Code:
<div id="parent"><div id="child">Content here</div></div><style> #parent {position: relative;} #child {position: absolute;top: 0;bottom: 0;left: 0;right: 0;width: 50%;height: 30%;margin: auto;}</style>
5. Equal top and bottom padding
Code:
<div id="parent"><div id="child">Content here</div></div><style> #parent {padding: 5% 0;}#child {padding: 10% 0;}</style>
6. General Purpose of floater Div
Code:
<div id="parent"><div id="floater"></div><div id="child">Content here</div></div><style>#parent {height: 250px;}#floater {float: left;height: 50%;width: 100%;margin-bottom: -50px;}#child {clear: both;height: 100px;}</style>
Six vertical center Div Methods