如何用CSS阻止含内部表格的.main div撑高视口高度
当内部表格高度增加时,.main容器会被撑开,导致整个视口高度变大。我需要维持header-main-footer的固定结构,保持视口高度始终为100vh,让.tableContainer区域在内容过多时可以滚动。目前已经给body设置了max-height:100vh,但视口还是会被撑高。
HTML代码
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Prova stupida</title> <link rel="stylesheet" href="style.css"> </head> <body> <header> Header </header> <div class="main"> <div class="tableContainer"> <table cellspacing="0"> <thead> <tr><th>Ciao</th><th>come</th><th>va</th><th>?</th></tr> </thead> <tbody> <!-- 更多表格内容省略 --> <tr><td>Bene</td><td>grazie</td><td>a te</td><td>?</td></tr> </tbody> </table> </div> </div> <footer> Footer </footer> </body> </html>
原始CSS代码
* { margin: 0; padding: 0; } body { display: flex; flex-direction: column; max-height: 100vh; } header, footer { background-color: #35393C; padding: 20px; text-transform: uppercase; color: white; font-size: 24px; } .main { background-color: #42858C; flex-grow: 1; padding: 20px; } table { font-size: large; } table td { background-color: #397367; border: 1px solid black; padding: 10px 5px; } table th { background-color: #5DA399; padding: 10px 5px; }
解决方案
只需要调整以下CSS规则,就能实现需求:
- 修正body的高度限制:把
max-height:100vh改为height:100vh,同时添加overflow:hidden,强制body占满视口高度且不出现整体滚动条:
body { display: flex; flex-direction: column; height: 100vh; overflow: hidden; }
- 限制.main容器的范围:给
.main添加overflow:hidden,避免它被内部内容撑开超出分配的空间,同时加box-sizing:border-box确保padding不会额外增加容器高度:
.main { background-color: #42858C; flex-grow: 1; padding: 20px; overflow: hidden; box-sizing: border-box; }
- 设置.tableContainer的滚动属性:给
.tableContainer设置height:100%和overflow-y:auto,让内容超出时在容器内垂直滚动:
.tableContainer { height: 100%; overflow-y: auto; }
修改后的完整CSS代码
* { margin: 0; padding: 0; } body { display: flex; flex-direction: column; height: 100vh; overflow: hidden; } header, footer { background-color: #35393C; padding: 20px; text-transform: uppercase; color: white; font-size: 24px; } .main { background-color: #42858C; flex-grow: 1; padding: 20px; overflow: hidden; box-sizing: border-box; } .tableContainer { height: 100%; overflow-y: auto; } table { font-size: large; width: 100%; /* 可选,让表格填满容器宽度 */ } table td { background-color: #397367; border: 1px solid black; padding: 10px 5px; } table th { background-color: #5DA399; padding: 10px 5px; }
调整后,header和footer会固定在视口顶部和底部,.main容器占满中间剩余空间,.tableContainer在内容过多时会显示垂直滚动条,整体视口高度保持100vh不变。
内容的提问来源于stack exchange,提问作者Ascanio Donati
相关产品推荐
相关产品推荐

