You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Bootstrap 5.3中实现头部置顶、底部置底且主体占满中间区域

Bootstrap 5.3 固定头脚+主体填充布局解决方案

第一步:修正HTML结构错误

你的代码中<body>标签被错误嵌套在<head>内部,这会导致浏览器解析异常,先将<body>移到<head>外部。

第二步:实现目标布局

利用Bootstrap 5的工具类和Flex布局,直接实现头部固定顶部、底部固定底部,主体填充剩余空间的效果:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Test Webpage</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js"></script>
    <style>
        /* 根据实际需求调整头部、底部高度及对应内边距 */
        body {
            padding-top: 56px;
            padding-bottom: 56px;
        }
        header, footer {
            height: 56px;
            display: flex;
            align-items: center;
            padding: 0 1rem;
        }
    </style>
</head>
<body class="d-flex flex-column min-vh-100" style="background-color: rgb(100,100,100);">
    <header class="fixed-top" style="background-color: rgb(210, 210, 241);">
        Header
    </header>
    <main class="flex-grow-1" style="background-color: rgb(185, 185, 215);">
        Main content
    </main>
    <footer class="fixed-bottom" style="background-color: rgb(235, 235, 255);">
        Footer
    </footer>
</body>
</html>

关键实现说明

  • fixed-top/fixed-bottom:Bootstrap内置类,快速实现元素固定在视口顶部/底部
  • d-flex flex-column min-vh-100:让<body>成为垂直方向的Flex容器,高度至少占满整个视口
  • flex-grow-1:让<main>区域自动填充头部和底部之间的剩余空间,即使内容不足也能撑满中间区域
  • 自定义的padding和height:避免页面内容被固定的头部、底部遮挡,可根据实际设计调整数值

内容的提问来源于stack exchange,提问作者Riskhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 10:54:51