Home > Article > Web Front-end > 6 ways to center CSS vertically_html/css_WEB-ITnose
Reposted from
Using CSS to horizontally center elements is relatively simple. Row-level elements set the text-align center of their parent elements, and block-level elements set their own left and right. Just set margins to auto. This article collects six methods for vertically centering elements using CSS. Each method is suitable for different situations. Just choose a certain method in the actual use process.
Trial: Single line text vertically centered, demo
Code:
html
123 | <div id="parent"> <div id="child">Text here</div> </div> |
css
123 | #child { line-height: 200px; } |
Vertically center an image, the code is as follows
html
123 | <div id="parent"> <img src="image.png" alt="" /> </div> |
css
123456 | #parent { line-height: 200px; } #parent img { vertical-align: middle; } |
Applicable: Universal, demo
Code:
html
123 | <div id="parent"> <div id="child">Content here</div> </div> |
css
12345 | #parent {display: table;} #child { display: table-cell; vertical-align: middle; } |
Lower versions of IE fix bug:
123 | #child { display: inline-block; } |
Applicable to: block-level elements, demo
Code:
html
123 | <div id="parent"> <div id="child">Content here</div> </div> |
css
123456789 | #parent {position: relative;} #child { position: absolute; top: 50%; left: 50%; height: 30%; width: 50%; margin: -15% 0 0 -25%; } |
Applicable: Universal , but it does not work properly when IE version is lower than 7, demo
code:
html
123 | <div id="parent"> <div id="child">Content here</div> </div> |
css
1234567891011 | #parent {position: relative;} #child { position: absolute; top: 0; bottom: 0; left: 0; right: 0; width: 50%; height: 30%; margin: auto; } |
Applicable: Universal, demo
Code:
html
123 | <div id="parent"> <div id="child">Content here</div> </div> |
css
123456 | #parent { padding: 5% 0; } #child { padding: 10% 0; } |
Applicable: universal, demo
Code:
html
1234 | <div id="parent"> <div id="floater"></div> <div id="child">Content here</div> </div> |
css
1234567891011 | #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. Please refer to the article "vertical-centering".