萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS 佈局實戰:上中下三行,中間自適應高度並垂直居中

經典佈局需求:頁面分為頂部、中間、底部三區;頂底固定高度,中間區塊自適應瀏覽器剩餘高度,且內容垂直居中。兼容 Firefox 2.0、IE6/7、Opera 8.5、Safari。

核心思路

  • 現代瀏覽器:用 display:table/table-row/table-cell 模擬表格佈局,利用 vertical-align:middle 實現垂直居中
  • IE6/7:不支援 table 顯示模式,改用絕對定位 + 相對定位偏移 50% 實現居中

完整代碼

<!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=gb2312" />
<title>上中下三行自適應垂直居中</title>
<style type="text/css">
* { margin:0; padding:0; }
html, body, #box { height:100%; font:small/1.5 "宋體", serif; }
body { text-align:center; }
#box { 
  text-align:left; background:#666; display:table; width:80%; margin:0 auto; position:relative; 
}
#box > div { display:table-row; }
#header, #footer { background:#fcc; height:50px; }
#main { background:#ccf; }
#main #wrap { display:table-cell; background:#ffc; vertical-align:middle; }
#text { text-align:center; }
</style>
<!--[if IE]>
<style type="text/css">
#header, #footer { width:100%; z-index:3; position:absolute; }
#footer { bottom:0; }
#main { height:100%; z-index:1; position:relative; }
#main #wrap { position:absolute; top:50%; width:100%; text-align:left; }
#main #text { position:relative; width:100%; top:-50%; background:#ccc; }
</style>
<![endif]-->
</head>
<body>
<div id="box">
  <div id="header">header</div>
  <div id="main">
    <div id="wrap">
      <div id="text">
        <p>內容內容</p><p>內容內容</p><p>內容內容</p><p>內容內容</p>
        <p>內容內容</p><p>內容內容</p><p>內容內容</p><p>內容內容</p>
        <p>內容內容</p><p>內容內容</p><p>內容內容</p><p>內容內容</p>
      </div>
    </div>
  </div>
  <div id="footer">footer</div>
</div>
</body>
</html>

關鍵點解析

瀏覽器關鍵屬性原理
現代瀏覽器display:table/table-row/table-cell + vertical-align:middle模擬表格單元格垂直居中特性
IE6/7position:absolute; top:50% + position:relative; top:-50%外層下移 50%,內層上移 50% 抵消,達到垂直居中

現代最佳實踐(Flexbox/Grid)

新專案請直接使用 Flexbox:

.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}
.main { flex: 1; display: flex; align-items: center; justify-content: center; }

本文方案僅供維護舊專案參考。

copyright © 萬盛學電腦網 all rights reserved