預設情況下,div 高度由內容撐開。但當內容為浮動元素、絕對定位或需填滿視窗高度時,容器高度會塌陷。本文整理從傳統到現代的解決方案。
overflow: hidden/auto觸發 BFC(塊級格式化上下文),使父層包含浮動子元素。
.clearfix::after { content:""; display:block; clear:both; }
div 清除<div style="clear:both"></div>(不推薦,污染 HTML)。
.parent { display: flex; flex-direction: column; min-height: 100vh; }
.content { flex: 1; } /* 佔滿剩餘高度 */
.parent { display: grid; grid-template-rows: auto 1fr auto; min-height: 100vh; }
.full-height { min-height: 100vh; } /* 或 100dvh 解決移動端地址欄問題 */
<html>
<head>
<style type="text/css" media="screen">
body { background:#e1ddd9; font:12px Verdana; color:#564b47; padding:20px; margin:0; text-align:center; }
#content { text-align:left; vertical-align:middle; margin:0 auto; padding:0; width:550px; background:#fff; border:1px dashed #564b47; }
p, h1, pre { margin:0; padding:5px 10px; }
h1 { font-size:11px; text-transform:uppercase; text-align:right; color:#564b47; background:#90897a; }
a { color:#ff66cc; font-size:11px; text-decoration:none; }
pre { color:#564b47; font-size:11px; }
</style>
</head>
<body>
<div id="content">...內容...</div>
</body>
</html>
| 場景 | 推薦方案 |
|---|---|
| 包含浮動子元素 | overflow:hidden 或 clearfix |
| 視窗高度自適應 | Flexbox / Grid + min-height:100vh |
| IE9+ 專案 | Flexbox(加前綴) |
| 現代專案 | Grid / Flexbox 原生 |