反覆調整之後,我終於整理出一套解決 DIV 垂直居中的可行辦法,在這裡與大家分享。
核心思路是:先讓 html、body 撐滿整個視窗高度,再用一個「占位層」把上半屏撐起來,最後讓真正的內容層以負的 margin 抵消掉自身高度的一半,從而在垂直方向上恰好居中。關鍵代碼如下:
<!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;
text-align: center;
min-width: 402px
}
.FirstDIV
{
margin-top: -100px; /* SecondDIV 高度的一半 */
float: left;
width: 100%;
height: 50%;
}
.SecondDIV
{
clear: both;
border: silver 1px solid;
background: #666;
margin-left: auto;
overflow: auto;
width: 400px;
margin-right: auto;
height: 200px;
text-align: left
}
</style>
</head>
<body>
<div class="FirstDIV"></div>
<div class="SecondDIV">
<p>看看,這不就居中了。呵呵。而且沒有問題哦。www.Webjx.com </p>
</div>
</body>
</html>
這種做法的好處在於:內容層的高度可以是未知的,只要把 margin-top 設為其高度的一半即可實現垂直居中。
另一種常見思路是直接對元素做絕對定位,再用負 margin 把它拉回中心,寫法如下:
body{ background-color:#FFF5F0}
div{ position:absolute; top:50%; left:50%; margin:-100px 0 0 -200px;
width:400px; height:200px; border:1px #CCCC00 solid; font-family:Arial, Helvetica, sans-serif; color:#666666 }
這種方式直觀明瞭,但需要事先知道元素確切的寬高,才能計算出正確的負 margin 值。