水平居中靠 margin:0 auto 就能解決,垂直居中的麻煩程度卻完全不在同一個量級——尤其當你事先不知道那個方塊會有多高。折騰了一輪之後,找到一個乾淨又穩定的做法,記錄在這裡。
先用一個佔位層把上半個視窗吃掉,讓真正的內容塊落在中線上,再把它往上拉半個自身高度。關鍵在於:那個「半個自身高度」必須寫成負的 margin-top,而高度是我們自己定好的已知值。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CSS布局技巧:未知高度div 垂直居中的問題</title>
<style type="text/css">
html, body {
height: 100%;
padding: 0;
margin: 0;
}
body {
min-height: 200px;
min-width: 402px;
text-align: center;
}
.FirstDIV {
float: left;
width: 100%;
height: 50%;
margin-top: -100px; /* SecondDIV 高度的一半 */
}
.SecondDIV {
clear: both;
width: 400px;
height: 200px;
margin-left: auto;
margin-right: auto;
overflow: auto;
border: silver 1px solid;
background: #666;
text-align: left;
}
</style>
</head>
<body>
<div class="FirstDIV"></div>
<div class="SecondDIV">
<p>看看,這不就居中了。而且沒有問題哦。</p>
</div>
</body>
</html>
[Ctrl+A 全部選擇 提示:你可先修改部分代碼,再按運行]
html, body { height:100% }:把高度鏈一路打通,百分比高度才有依據。.FirstDIV:一個空標籤,佔掉視窗上半部,同時用 margin-top:-100px 把它往上收 100px,於是它的下邊界正好落在視窗垂直中線。這裡的 100px 就是 SecondDIV 高度 200px 的一半。.SecondDIV:用 clear:both 甩開浮動影響,再用左右 auto 完成水平居中。如果不介意用絕對定位,兩行就能收工:
div {
position: absolute;
top: 50%;
left: 50%;
margin: -100px 0 0 -200px;
width: 400px;
height: 200px;
}
邏輯完全相同——先用 50% 把左上角推到中心,再用負 margin 扣掉自身尺寸的一半。兩種做法都要求高度已知;真正要應對「高度未知」的場景,得靠 table-cell 或 transform 這類更現代的技巧,那是另一個話題了。