.wrap {
display: table;
width: 760px; height: 400px;
border: 1px solid #f09;
background: #fcf;
}
.subwrap {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.content { display: inline-block; /* 或保持原樣 */ }
原理:display: table + display: table-cell 模擬表格儲存格,vertical-align: middle 即可垂直置中。
.wrap { *position: relative; overflow: hidden; } /* IE6/7 */
.subwrap { *position: absolute; *top: 50%; } /* IE6/7 */
.content { *position: relative; *top: -50%; } /* IE6/7 */
relative 建立定位基準。absolute; top: 50% 移至容器垂直中心。relative; top: -50% 向上位移自身高度一半,完成置中。<div id="wrap">
<div id="subwrap">
<div id="content">垂直置中內容</div>
</div>
</div>
.wrap {
display: flex;
align-items: center;
justify-content: center;
min-height: 400px;
}
Flexbox 單層結構即可水平垂直雙向置中,IE10+ 全支援,維護性遠優於 table-cell/Hack 方案。