1. 程式人生 > >div 垂直居中的六種方法

div 垂直居中的六種方法

利用CSS進行元素的水平居中,比較簡單,行級元素設定其父元素的text-align center,塊級元素設定其本身的left 和 right margins為auto即可。本文收集了六種利用css進行元素的垂直居中的方法,每一種適用於不同的情況,在實際的使用過程中選擇某一種方法即可。

Line-Height Method

line height demo
試用:單行文字垂直居中,demo

程式碼:

html

1
2
3
<div id="parent">
<div id="child">Text here</div>
</div>

css

1
2
3
#child
{ line-height: 200px; }

垂直居中一張圖片,程式碼如下

html

1
2
3
<div id="parent">
<img src="image.png" alt="" />
</div>

css

1
2
3
4
5
6
#parent {
line-height: 200px;
}
#parent img {
vertical-align: middle;
}

CSS Table Method

table cell demo

適用:通用,demo

程式碼:

html

1
2
3
<div id="parent">
<div
id="child">
Content here</div> </div>

css

1
2
3
4
5
#parent {display: table;}
#child {
display: table-cell;
vertical-align: middle;
}

低版本 IE fix bug:

1
2
3
#child {
display: inline-block;
}

Absolute Positioning and Negative Margin

absolute positioning and negative margin demo

適用:塊級元素,demo

程式碼:

html

1
2
3
<div
id="parent">
<div id="child">Content here</div> </div>

css

1
2
3
4
5
6
7
8
9
#parent {position: relative;}
#child {
position: absolute;
top: 50%;
left: 50%;
height: 30%;
width: 50%;
margin: -15% 0 0 -25%;
}

Absolute Positioning and Stretching

absolute positioning and vertical stretching demo

適用:通用,但在IE版本低於7時不能正常工作,demo

程式碼:

html

1
2
3
<div id="parent">
<div id="child">Content here</div>
</div>

css

1
2
3
4
5
6
7
8
9
10
11
#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

vertical centering with padding demo

適用:通用,demo

程式碼:

html

1
2
3
<div id="parent">
<div id="child">Content here</div>
</div>

css

1
2
3
4
5
6
#parent {
padding: 5% 0;
}
#child {
padding: 10% 0;
}

Floater Div

vertical centering with floater div demo

適用:通用,demo

程式碼:

html

1
2
3
4
<div id="parent">
<div id="floater"></div>
<div id="child">Content here</div>
</div>

css

1
2
3
4
5
6
7
8
9
10
11
#parent {height: 250px;}
#floater {
float: left;
height: 50%;
width: 100%;
margin-bottom: -50px;
}
#child {
clear: both;
height: 100px;
}