在版面設計中,常會遇到文字或圖片需要垂直置中的情況。若是單行文字,可用高度與行高相同的方式處理;但遇到多行文字、固定高度容器或未知高度容器時,就需要更完整的解法。
如果容器內只有一行文字,最簡單的方式是讓 height 與 line-height 相同。
<div style="height:25px; line-height:25px; overflow:hidden;">
單行文字
</div>
在現代瀏覽器中,可使用表格顯示模式來模擬儲存格垂直置中。
.wrapper {
height: 400px;
display: table;
}
.content {
vertical-align: middle;
display: table-cell;
width: 760px;
}
對應 HTML:
<div class="wrapper">
<div class="content">
多行文字內容
</div>
</div>
這種做法可讓內容在固定高度容器中垂直置中,但舊版 IE 不支援 display:table 與 display:table-cell。
若需要相容 IE6、IE7,可改用絕對定位與相對定位搭配。先讓父層定位,再讓子層以百分比位移。
.wrap {
width: 760px;
height: 400px;
position: relative;
}
.subwrap {
position: absolute;
top: 50%;
}
.content {
position: relative;
top: -50%;
}
這種方式利用父元素 top:50% 與子元素 top:-50% 互相抵消,讓內容接近垂直置中。
實務上可先用表格顯示模式處理標準瀏覽器,再用 IE 專屬 hack 補上定位方案:
.wrap {
display: table;
width: 760px;
height: 400px;
*position: relative;
overflow: hidden;
}
.subwrap {
vertical-align: middle;
display: table-cell;
*position: absolute;
*top: 50%;
}
.content {
*position: relative;
*top: -50%;
}
若內容高度未知,可讓外層使用表格模式,內層作為儲存格並設定垂直置中;舊版 IE 則改用定位方式。
html, body {
height: 100%;
}
.wrapper {
width: 100%;
height: 100%;
display: table;
text-align: center;
}
.subwrap {
display: table-cell;
vertical-align: middle;
}
* html .wrapper {
position: absolute;
top: 50%;
width: 100%;
display: block;
height: auto;
}
* html .subwrap {
position: relative;
top: -50%;
}
*+html .wrapper {
position: absolute;
top: 50%;
width: 100%;
display: block;
height: auto;
}
*+html .subwrap {
position: relative;
top: -50%;
}
對應 HTML:
<div class="wrapper">
<div class="subwrap">
<div class="content">
未知高度內容垂直置中
</div>
</div>
</div>
垂直置中並沒有單一萬用寫法。單行文字可用行高;固定高度多行文字可用表格模式或定位;未知高度則需搭配外層表格模式與內層儲存格。若仍需支援舊版 IE,則要額外加入定位 hack。