要实现在内容很少时保持 footer 在最下方,而内容很多时在所有内容底部,可以使用CSS的Flex布局。这样可以确保在页面内容不足以填满整个视口时,footer 保持在视口底部,而在内容超出视口时,footer 在所有内容底部。
下面是使用 Flexbox 的示例代码:
HTML 结构:
- <!DOCTYPE html>
- <html>
-
- <head>
- <!-- 页面头部信息 -->
- <style>
- html,
- body {
- height: 100%;
- margin: 0;
- padding: 0;
- }
-
- body {
- display: flex;
- flex-direction: column;
- background-color: #ccc;
- }
-
- h1,
- h2 {
- color: #fff;
- text-align: center;
- }
-
- .container {
- flex: 1;
- background: #333;
- }
-
- .footer {
- /* 可根据需要设置 footer 的背景颜色 */
- background-color: #666;
- }
- </style>
- </head>
-
- <body>
- <header>
- <h1>Title</h1>
- </header>
- <div class="container">
- <h2>Content</h2>
- <!-- 网页内容放在这里 -->
- </div>
- <footer class="footer">
- <h2>Footer</h2>
- <!-- Footer 内容放在这里 -->
- </footer>
- </body>
-
- </html>
实现效果:
使用上面的 CSS,当页面内容很少时,footer 会保持在视口底部。而当内容很多时,footer 会在所有内容的底部,不会覆盖在内容上面。这样可以根据实际内容来灵活调整 footer 的位置。