要实现这个效果,可以使用 CSS 的 height: 100vh
和 overflow
属性来控制页面和组件的滚动行为。以下是具体的实现步骤:
1. 设置 html
和 body
高度
确保 html
和 body
始终占满整个视口(100% 高度),并且不允许滚动:
1 2 3 4 5
| html, body { height: 100vh; margin: 0; overflow: hidden; }
|
2. 让主容器也占满整个页面
然后,为你的主容器(例如 .container
)也设置 100% 高度:
1 2 3 4 5
| .container { display: flex; flex-direction: column; height: 100vh; }
|
3. 让内容超出的组件内部滚动
对于可能溢出的组件(例如 .content
),使用 overflow: auto;
使其内部滚动,而不是整个页面滚动:
1 2 3 4
| .content { flex: 1; overflow: auto; }
|
完整示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| <!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>固定页面高度 + 内部滚动</title> <style> html, body { height: 100vh; margin: 0; overflow: hidden; }
.container { display: flex; flex-direction: column; height: 100vh; }
.header { background: #333; color: white; padding: 10px; text-align: center; }
.content { flex: 1; overflow: auto; padding: 10px; background: #f0f0f0; }
.footer { background: #333; color: white; padding: 10px; text-align: center; } </style> </head> <body> <div class="container"> <div class="header">固定头部</div> <div class="content"> <p>这里是可滚动的内容区域</p> <p>这里是可滚动的内容区域</p> <p>这里是可滚动的内容区域</p> <p>这里是可滚动的内容区域</p> <p>这里是可滚动的内容区域</p> <p>这里是可滚动的内容区域</p> <p>这里是可滚动的内容区域</p> <p>这里是可滚动的内容区域</p> <p>这里是可滚动的内容区域</p> <p>这里是可滚动的内容区域</p> <p>这里是可滚动的内容区域</p> <p>这里是可滚动的内容区域</p> <p>这里是可滚动的内容区域</p> <p>这里是可滚动的内容区域</p> <p>这里是可滚动的内容区域</p> <p>这里是可滚动的内容区域</p> </div> <div class="footer">固定底部</div> </div> </body> </html>
|
效果说明
- 页面不会滚动(
overflow: hidden;
限制 body
)
- 组件
content
内部滚动(overflow: auto;
允许超出内容滚动)
- **固定的
header
和 footer
**,不会随着内容滚动