Use CSS to horizontally center elements. Row-level elements set the text-align center of their parent elements, and block-level elements set their own left. Just set right margins to auto. This article collects six methods of vertically centering elements using CSS, let’s take a look!
Line-Height Method
Trial: Single line text vertically centered, demo
Code:
html
<p id="parent"> <p id="child">Text here</p> </p>
css
#child { Line-height: 200px; }
Vertically center an image, the code is as follows
#html
##
css
#parent { Line-height: 200px; } #parent img { Vertical-align: middle; }CSS Table Method
Applicable: Universal, demoCode:html
Content here
css
#parent {display: table;} #child { Display: table-cell; Vertical-align: middle; }
Lower version IE fix bug:
#child { Display: inline-block; }
Absolute Positioning and Negative Margin
##Applicable to: block-level elements, democode :
html
Content here
css
#parent {position: relative;} #child { position: absolute; top: 50%; Left: 50%; Height: 30%; width: 50%; Margin: -15% 0 0 -25%; }Absolute Positioning and Stretching
##Applicable: universal, but does not work properly when IE version is lower than 7, demo#
##Code:html
Content here
css
#parent {position: relative;} #child { position: absolute; top: 0; bottom: 0; left: 0; Right: 0; width: 50%; Height: 30%; margin: auto; }
Equal Top and Bottom PaddingApplicable: Universal, demo
Code:html
Content here
css
#parent { padding: 5% 0; } #child { padding: 10% 0; }
Floater p
Applicable: Universal, demo
Code:
html
<p id="parent"> <p id="floater"></p> <p id="child">Content here</p> </p>
css
#parent {height: 250px;} #floater { float: left; height: 50%; width: 100%; Margin-bottom: -50px; } #child { Clear: both; height: 100px; }
The above are the six methods, which can be chosen reasonably during actual use.
For more programming-related knowledge, please visit:Introduction to Programming! !