標籤:css垂直置中
利用CSS進行元素的水平置中,比較簡單,行級元素設定其父元素的text-align center,區塊層級元素設定其本身的left 和 right margins為auto即可。本文收集了六種利用css進行元素的垂直置中的方法,每一種適用於不同的情況,在實際的使用過程中選擇某一種方法即可。
Line-Height Method
650) this.width=650;" src="http://www.vanseodesign.com/blog/wp-content/uploads/2011/07/line-height.png" alt="line height demo" height="231" width="465" style="border:none;" />
試用:單行文本垂直置中,demo
代碼:
html
123 |
<div id="parent"><div id="child">Text here</div></div> |
css
123 |
#child {line-height: 200px;} |
垂直置中一張圖片,代碼如下
html
123 |
<div id="parent"><img src="image.png" /></div> |
css
123456 |
#parent {line-height: 200px;}#parent img {vertical-align: middle;} |
CSS Table Method
650) this.width=650;" src="http://www.vanseodesign.com/blog/wp-content/uploads/2011/07/table-cell.png" alt="table cell demo" height="233" width="465" style="border:none;" />
適用:通用,demo
代碼:
html
123 |
<div id="parent"><div id="child">Content here</div></div> |
css
12345 |
#parent {display: table;}#child {display: table-cell;vertical-align: middle;} |
低版本 IE fix bug:
123 |
#child {display: inline-block;} |
Absolute Positioning and Negative Margin
650) this.width=650;" src="http://www.vanseodesign.com/blog/wp-content/uploads/2011/07/positioning-margin.png" alt="absolute positioning and negative margin demo" style="border:none;" />
適用:區塊層級元素,demo
代碼:
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
650) this.width=650;" src="http://www.vanseodesign.com/blog/wp-content/uploads/2011/07/positioning-stretch.png" alt="absolute positioning and vertical stretching demo" style="border:none;" />
適用:通用,但在IE版本低於7時不能正常工作,demo
代碼:
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
650) this.width=650;" src="http://www.vanseodesign.com/blog/wp-content/uploads/2011/07/padding.png" alt="vertical centering with padding demo" style="border:none;" />
適用:通用,demo
代碼:
html
123 |
<div id="parent"><div id="child">Content here</div></div> |
css
123456 |
#parent {padding: 5% 0;}#child {padding: 10% 0;} |
Floater Div
650) this.width=650;" src="http://www.vanseodesign.com/blog/wp-content/uploads/2011/07/floater-div.png" alt="vertical centering with floater div demo" style="border:none;" />
適用:通用,demo
代碼:
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;} |
以上就是六種方法,可以在實際的使用過程中合理選擇,參考文章《vertical-centering》。
本文出自 “劉博方的部落格” 部落格,請務必保留此出處http://liubofang.blog.51cto.com/11162557/1868233
CSS 元素垂直置中的 6種方法