經典方案:佔位浮動元素 + 絕對定位內容
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<title>未知高度 DIV 垂直置中</title>
<style>
html, body { height: 100%; margin: 0; padding: 0; }
body { min-height: 200px; text-align: center; min-width: 402px; }
.FirstDIV {
float: left; width: 100%; height: 50%;
margin-top: -100px; /* 內容區高度一半(負值) */
}
.SecondDIV {
clear: both;
width: 400px; height: 200px; /* 已知高度 */
margin: 0 auto;
border: 1px solid silver;
background: #666;
overflow: auto;
text-align: left;
}
</style>
</head>
<body>
<div class="FirstDIV"></div>
<div class="SecondDIV">
<p>看看,這不就置中了。而且沒有問題哦。</p>
<p>對比:absolute top:50% + margin 負值需知高度。</p>
</div>
</body>
</html>
原理解析
.FirstDIV 浮動、高度 50%、負頂部邊距為內容區高度一半(-100px),將視覺基準線拉至視窗垂直中心偏上 100px。
.SecondDIV clear:both 清除浮動,寬高固定,margin:0 auto 水平置中,頂部緊接 .FirstDIV 底部,剛好垂直置中。
- 內容高度超出時
overflow:auto 產生捲軸,不破壞置中。
已知高度的簡單方案
.box {
position: absolute; top: 50%; left: 50%;
width: 400px; height: 200px;
margin: -100px 0 0 -200px; /* 負邊距為自身高寬一半 */
}
現代最佳方案(不限高度)
Flexbox
.container {
display: flex; justify-content: center; align-items: center;
min-height: 100vh;
}
Grid
.container { display: grid; place-items: center; min-height: 100vh; }
Transform(IE9+)
.box { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
選擇建議
- 現代專案:Flexbox/Grid,語意清晰、無魔法數字。
- 需支援 IE8-9:Transform 方案。
- 極舊環境:佔位浮動法 或
display:table-cell(需外層 display:table)。