The use of CSS for the horizontal center of elements, relatively simple, row-level elements set its parent element of the Text-align Center, block-level elements set its own left and right margins for auto. This paper collects six methods of vertical centering of elements using CSS, each of which is suitable for different situations and chooses a certain method in the actual use process.
Line-height Method
Trial: Single-line text vertically centered, demo
Code:
Html
123 |
<id=' parent ' ><id=' child ' >text here</div> </div> |
Css
Center a picture vertically, the code is as follows
Html
123 |
<ID="parent" ><src=alt=/></div> |
Css
123456 |
{line-height200px;} {vertical-alignmiddle;} |
CSS Table Method
Applicable: General, demo
Code:
Html
123 |
<id=' parent ' ><id=' child ' >content here</div> </div> |
Css
12345 |
{display: Table;} {displayTable-cell; Vertical-alignmiddle;} |
Low version of IE fix bug:
123 |
{display: inline-block;} |
Absolute positioning and negative Margin
For: block-level elements, demo
Code:
Html
123 |
<id=' parent ' ><id=' child ' >content here</div> </div> |
As1
123456789 |
#parent{position: relative;} #child {position: Absolute; Top50%; Left50%; Height30%; Width50%; Margin-15% 0 0 -25%< Span class= "sy0" >; /span> |
Absolute Positioning and stretching
Applicable: general, but does not work correctly when IE version is less than 7, demo
Code:
Html
123 |
<id=' parent ' ><id=' child ' >content here</div> </div> |
As1
1234567891011 |
#parent{Position:Relative;} #child {position: Span class= "kw2" >absolute; Top0; Bottom0; Left0; Right0; Width50%; Height30%; Marginauto;} |
Equal Top and Bottom Padding
Applicable: General, demo
Code:
Html
123 |
<id=' parent ' ><id=' child ' >content here</div> </div> |
Css
123456 |
{padding0;} {padding0;} |
Floater Div
Applicable: General, demo
Code:
Html
1234 |
<ID="parent" ><id="Floater" ></div><ID =' child ' >content here</div></div> |
Css
1234567891011 |
#parent{height: 250px;} #floater {float: left< Span class= "sy0" >; height: 50%; Width100%; Margin-bottom-50px;} #child {clear: both< Span class= "sy0" >; height: 100px;} |
The above is six kinds of methods, can be used in the actual process of reasonable choice, reference to the article "Vertical-centering".
Go 6 ways to center CSS elements vertically