如何使用Bootstrap 5将页脚固定在屏幕底部?
当前代码里Footer使用position: relative定位,这种定位会跟随文档流,当页面内容高度小于屏幕高度时,Footer就会停在内容下方而非屏幕底部。以下两种方案可解决该问题:
方案一:固定在视口底部(滚动时始终显示)
将Footer的定位改为fixed,同时给Body添加底部内边距,避免页面内容被Footer遮挡:
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> <body style="padding-bottom: 45px;"> <!-- 页面内容容器 --> <div class="container">页面内容</div> <div class="container">更多内容</div> <footer id="footer"> <div style="background: black; text-align: center; margin: 0; padding: 10px; height: 45px; position: fixed; left: 0; right: 0; bottom: 0;"> <p style="color:white; font-family: raleway; margin: 0;">Text</p> </div> </footer> </body>
方案二:粘性Footer(内容不足时在视口底部,内容足够时跟随到页面底部)
采用Flexbox布局,让中间内容容器占满剩余空间,Footer自动吸附到底部:
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> <body style="display: flex; flex-direction: column; min-height: 100vh; margin: 0;"> <!-- 中间内容容器设置flex-grow:1,占满剩余空间 --> <div class="container" style="flex-grow: 1;">页面内容</div> <div class="container" style="flex-grow: 1;">更多内容</div> <footer id="footer"> <div style="background: black; text-align: center; margin: 0; padding: 10px; height: 45px; width: 100%;"> <p style="color:white; font-family: raleway; margin: 0;">Text</p> </div> </footer> </body>
方案选择说明
- 方案一适合需要Footer始终可见的场景,比如底部导航栏;
- 方案二适合希望Footer仅在页面内容较短时停在视口底部,不遮挡长页面内容的场景。
内容的提问来源于stack exchange,提问作者Frigidissima
相关产品推荐
相关产品推荐

