Flexbox布局问题:实现仅主内容区滚动,头部底部侧边栏固定
Flexbox布局:实现固定侧边栏与独立滚动的主内容区
需求与问题
需求:
- header和footer始终固定在视口顶部、底部,保持可见
- 仅橙色的
contentdiv内部可滚动,且该div需占满可用高度(内容不足时也填满) - 左右侧边栏、header、footer不随滚动移动
当前问题:滚动主内容时,侧边栏会同步滚动,不符合预期。
修改后的代码
CSS 代码
body { margin: 0; padding: 0; } .flex-container { display: flex; flex-direction: column; height: 100vh; background-color: lightblue; } header { background-color: lightcoral; width: 100%; } main { background-color: lightcyan; flex: 1 1 auto; /* 移除main的全局滚动,将滚动权限交给content */ } footer { background-color: lightgoldenrodyellow; width: 100%; } .flex-column-container { display: flex; height: 100%; /* 让容器占满main的全部可用高度 */ } .col1 { flex-grow: 1; background-color: lightgray; } .col2 { flex-grow: 4; background-color: lightgreen; padding: 20px; display: flex; flex-direction: column; /* 垂直布局,让content自动填充剩余高度 */ } .col3 { flex-grow: 1; background-color: lightpink; } .content { background-color: lightsalmon; flex: 1; /* 占满col2的剩余高度,替代原min-height:100% */ padding: 20px; overflow-y: auto; /* 仅content内部内容溢出时滚动 */ }
HTML 代码(无需大幅修改)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Flexbox Layout</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="flex-container"> <header>This is a header</header> <main> <div class="flex-column-container"> <div class="col1"> Left sidenav </div> <div class="col2"> Main <div class="content"> Main content div. <br> I want this div to occupy the remaining height without expanding the flexbox layout. I would like the div to have an overflow when the content is bigger than the layout space available. I don't want the sidenavs to be scrolled too as they scroll right now. <br><br><br><br><br><br><br><br><br><br><br><br><br><br> <br><br><br><br><br><br><br><br><br><br><br><br><br><br> <br><br><br><br><br><br><br><br><br><br><br><br><br><br> <br><br><br><br><br><br><br><br><br><br><br><br><br><br> End of this section. </div> </div> <div class="col3"> Right sidenav </div> </div> </main> <footer>This is the footer</footer> </div> </body> </html>
关键修改说明
- 移除main的全局滚动:删掉
main的overflow-y: auto,避免整个主区域带动侧边栏滚动 - 让侧边栏容器占满高度:给
.flex-column-container设置height: 100%,确保侧边栏与主内容区等高 - 垂直布局col2:将
.col2设为垂直flex容器,内部的content通过flex:1自动填充剩余高度 - content独立滚动:用
flex:1替代min-height:100%保证高度填充,同时通过overflow-y: auto实现内容溢出时仅内部滚动
内容的提问来源于stack exchange,提问作者Omar RB
相关产品推荐
相关产品推荐

