<div id="wrapper">
<div id="cell">
<div class="content">內容區</div>
</div>
</div>
#wrapper { display: table; }
#cell { display: table-cell; vertical-align: middle; }
<div class="content">內容區</div>
.content {
position: absolute;
top: 50%;
height: 240px; /* 必須固定高度 */
margin-top: -120px; /* 負的一半高度 */
overflow: auto; /* 內容過多出現滾動條 */
}
<div id="floater">
<div id="content">內容區</div>
</div>
#floater { float: left; height: 50%; margin-bottom: -120px; }
#content { clear: both; height: 240px; position: relative; }
#floater 元素;需固定內容高度| 場景 | 推薦方案 |
|---|---|
| 現代項目、內容高度不固定 | 方案一(配合 Flexbox 更佳) |
| 需兼容舊 IE、高度固定、結構極簡 | 方案二 |
| 需兼容舊 IE、高度固定、縮窗不截斷 | 方案三 |
補充:現代項目首選 Flexbox(display:flex; align-items:center; justify-content:center;)或 Grid,一行代碼解決所有痛點。