利用CSS進行元素的水平居中,比較簡單,行級元素設置其父元素的text-align center,塊級元素設置其本身的left 和 right margins為auto即可。本文收集了六種利用css進行元素的垂直居中的方法,每一種適用於不同的情況,在實際的使用過程中選擇某一種方法即可。
一、
Line-Height Method
適用於設置行高 單行文本垂直居中,
<div id="parent"> <div id="child">Text here</div> </div> <style> #child {line-height: 200px;} </style>

如果垂直一張圖片代碼如下:
<div id="parent"> <img src="image.png" alt="" /> </div> #parent { line-height: 200px; } #parent img { vertical-align: middle; }
二、table-cell Method 通用
代碼如下:
<div id="parent"> <div id="child">Content here</div> </div> <style> #parent {display: table;} #child { display: table-cell; vertical-align: middle; } </style> <!--如果是IE8以下版本而要加以下css--> <style> #child{display:inline-block;} </style>

三、Absolute Positioning and Negative Margin 適用於塊級元素
代碼如下:
<div id="parent"> <div id="child">Content here</div> </div> <style> #parent {position: relative;} #child { position: absolute; top: 50%; left: 50%; height: 30%; width: 50%; margin: -15% 0 0 -25%; } </style>

四、Absolute Positioning and Stretching 通用,但在IE版本低於7時不能正常工作
代碼:
<div id="parent"> <div id="child">Content here</div> </div> <style> #parent {position: relative;} #child { position: absolute; top: 0; bottom: 0; left: 0; right: 0; width: 50%; height: 30%; margin: auto; } </style>

五、Equal Top and Bottom Padding 通用
代碼:
<div id="parent"> <div id="child">Content here</div> </div> <style> #parent { padding: 5% 0; } #child { padding: 10% 0; } </style>

六、Floater Div 通用
代碼:
<div id="parent"> <div id="floater"></div> <div id="child">Content here</div> </div> <style> #parent {height: 250px;} #floater { float: left; height: 50%; width: 100%; margin-bottom: -50px; } #child { clear: both; height: 100px; } </style>

