把 DIV 的 display 設為表格模式,就能借用表格的 vertical-align 屬性來實現垂直居中。
div#wrapper {
display: table;
width: 500px;
height: 500px;
background-color: #c00;
}
div#row {
display: table-row;
}
div#cell {
display: table-cell;
vertical-align: middle;
}
<div id="wrapper">
<div id="row">
<div id="cell">
If you want to sell sugar water for the rest of my life...
</div>
</div>
</div>
優點:不受內容高度限制,實現簡單;缺點:不相容 IE6、IE7。
將元素絕對定位,top 設為 50%,再用負的 margin-top 抵消自身高度的一半,前提是必須已知內容的固定高度。
div#wrapper {
position: relative;
width: 500px;
height: 500px;
background-color: #c00;
}
div#content {
position: absolute;
top: 50%;
left: 0;
width: 400px;
height: 300px;
margin-top: -150px;
background-color: pink;
}
優點:相容性好;缺點:必須事先知道內容高度。
方法三與方法二思路一致,只是透過一個額外占位元素撐開高度:
.wrap {
height: 500px;
width: 500px;
background-color: pink;
}
.additional {
height: 50%;
margin-bottom: -120px;
}
#content {
height:240px;
width:70%;
background-color: #000;
}
<div class="wrap">
<div class="additional"></div>
<div id="content"></div>
</div>
優缺點同方法二,只是多了一個額外標籤。
為固定寬高的元素同時設定 top:0; bottom:0;,由於它有確定高度,無法上下貼合,此時 margin:auto 會讓它自動居中:
#content {
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
margin:auto;
height:240px;
width:70%;
background-color: #000;
}
<div id="content">Content here</div>
優點:寫法非常簡潔;缺點:不相容 IE6、IE7。
若只是要讓單行文字垂直居中,只需把 line-height 設為與容器 height 相同的值即可,無需額外結構,是最省事的方案。