Home  >  Article  >  Web Front-end  >  6 ways to center CSS vertically_html/css_WEB-ITnose

6 ways to center CSS vertically_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:42:411204browse

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.

Line-Height Method


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; }

CSS Table Method

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; }

Absolute Positioning and Negative Margin

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%; }

Absolute Positioning and Stretching

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; }

Equal Top and Bottom Padding

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; }

Floater Div

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".

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn