垂直置中是 CSS 經典難題,本文整理五種主流方案,分析適用場景與優缺點,助你根據專案需求做最佳選擇。
.vertical { height: 100px; line-height: 100px; }
.vertical {
position: absolute; top: 50%; left: 50%;
width: 200px; height: 100px;
margin-top: -50px; margin-left: -100px;
}
.container { display: table; height: 300px; }
.content { display: table-cell; vertical-align: middle; }
IE6/7 相容寫法:多加一層 .tableCell,搭配 *position: absolute; *top: 50% Hack。
html, body { height: 100%; }
#floater { float: left; height: 50%; margin-bottom: -120px; } /* 高度一半負值 */
#content { clear: both; height: 240px; position: relative; }
.center { display: flex; align-items: center; justify-content: center; }