萬盛學電腦網

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

CSS display:table-cell 實現 DIV 垂直置中(含 IE6/7 兼容)

現代瀏覽器標準做法

.wrap {
  display: table;
  width: 760px; height: 400px;
  border: 1px solid #f09;
  background: #fcf;
}
.subwrap {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}
.content { display: inline-block; /* 或保持原樣 */ }

原理:display: table + display: table-cell 模擬表格儲存格,vertical-align: middle 即可垂直置中。

IE6/7 兼容 Hack

.wrap { *position: relative; overflow: hidden; }        /* IE6/7 */
.subwrap { *position: absolute; *top: 50%; }             /* IE6/7 */
.content { *position: relative; *top: -50%; }            /* IE6/7 */
  • 外層 relative 建立定位基準。
  • 中層 absolute; top: 50% 移至容器垂直中心。
  • 內層 relative; top: -50% 向上位移自身高度一半,完成置中。

完整結構

<div id="wrap">
  <div id="subwrap">
    <div id="content">垂直置中內容</div>
  </div>
</div>

現代替代方案(推薦)

.wrap {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 400px;
}

Flexbox 單層結構即可水平垂直雙向置中,IE10+ 全支援,維護性遠優於 table-cell/Hack 方案。

copyright © 萬盛學電腦網 all rights reserved