以下是實現頁面頂部和底部固定、中間內容自適應的幾種常見方法,附代碼示例和適用場景分析:
方法一:Flexbox 彈性布局
<body style="margin:0; min-height:100vh; display:flex; flex-direction:column;"><header style="height:60px; background:#ccc;">頂部固定</header><main style="flex:1; overflow-y:auto;">中間自適應內容</main><footer style="height:40px; background:#eee;">底部固定</footer>
</body>
特點:
- 現代瀏覽器首選方案
- 中間區域自動填充剩余空間
- 支持中間內容獨立滾動
方法二:CSS Grid 網格布局
<body style="margin:0; height:100vh; display:grid; grid-template-rows:60px 1fr 40px;"><header style="background:#ccc;">頂部固定</header><main style="overflow-y:auto;">中間自適應內容</main><footer style="background:#eee;">底部固定</footer>
</body>
特點:
- 二維布局能力更強
- 代碼簡潔直觀
- 適合復雜布局場景
方法三:絕對定位
<body style="margin:0;"><header style="position:fixed; top:0; width:100%; height:60px; background:#ccc;">頂部固定</header><main style="margin:60px 0 40px; height:calc(100vh - 100px); overflow-y:auto;">中間自適應內容</main><footer style="position:fixed; bottom:0; width:100%; height:40px; background:#eee;">底部固定</footer>
</body>
特點:
- 兼容性最好(支持IE8+)
- 需要手動計算高度
- 注意設置中間區域的外邊距
方法四:Viewport單位 + Calc
<style>header { height:10vh; background:#ccc; }footer { height:8vh; background:#eee; }main { height: calc(100vh - 18vh); overflow-y: auto;}
</style><header>頂部固定</header>
<main>中間自適應內容</main>
<footer>底部固定</footer>
特點:
- 響應式布局友好
- 需注意移動端瀏覽器地址欄的影響
- 建議配合媒體查詢使用
關鍵注意事項:
- 滾動處理:中間區域建議添加
overflow-y: auto
實現獨立滾動 - 高度計算:使用
100vh
時需考慮移動端瀏覽器地址欄的顯示/隱藏 - 層級問題:固定定位元素需設置
z-index
防止內容覆蓋 - 內容溢出:中間區域內容較多時需設置合理的滾動策略
- 瀏覽器兼容:Flexbox/Grid 方案需考慮目標瀏覽器支持情況
根據項目需求選擇方案:
- 現代項目推薦 Flexbox 或 Grid
- 需要兼容舊瀏覽器時選擇 絕對定位
- 響應式項目可嘗試 Viewport單位 方案