如何让可滚动的div填充搜索栏与底部按钮间的剩余空间
解决左侧产品区域填充剩余空间并可滚动的问题
问题出在布局高度控制和flex属性的使用上,调整以下几点就能解决:
修改步骤
- 给
main-container添加绝对定位,让它占满整个视口,为左侧栏提供完整的高度参考:.main-container { position: absolute; /* 新增 */ top: 0; right: 0; bottom: 0; left: 0; } - 让
left-row占满父容器高度,明确flex垂直布局:.left-row { width: 20%; border: 1px solid rgba(0, 0, 0, .125); display: flex; flex-direction: column; height: 100%; /* 占满main-container高度 */ } - 调整产品区域样式,用
flex:1填充剩余空间,设置垂直滚动替代固定高度:.border-top { flex: 1; /* 自动填充剩余空间 */ overflow-y: auto; /* 仅内容超出时显示垂直滚动条 */ } - 移除底部按钮的
fixed-bottom类,让它留在flex布局内,避免脱离文档流导致高度计算错误:<div class="add d-flex justify-content-center"> <a type="button" class="btn btn-primary w-100">Add</a> </div>
修改后的完整代码
CSS
body { overflow: hidden; margin: 0; /* 移除默认边距,避免布局偏移 */ } h5 { font-size: 1.2rem; } .main-container { position: absolute; top: 0; right: 0; bottom: 0; left: 0; } .left-row { width: 20%; border: 1px solid rgba(0, 0, 0, .125); display: flex; flex-direction: column; height: 100%; } .border-top { flex: 1; overflow-y: auto; } .products { border: none; } .add { border-top: 1px solid rgba(0, 0, 0, .125); border-right: 1px solid rgba(0, 0, 0, .125); padding: 1rem; background-color: rgb(242, 242, 242); } .card { margin-bottom: 1rem; } .card-body .card-body { height: 100px; } .hover:hover { cursor: pointer; }
HTML
<body> <div class="main-container d-flex flex-row"> <div class="left-row"> <div class="input-group justify-content-center p-3"> <input type="search" class="form-control" placeholder="Search" /> </div> <div class="border-top"> <div class="products card-body"> @foreach (Product product in Model.products) { <div class="card hover" style="display: flex"> <p>product</p> </div> } </div> </div> <div class="add d-flex justify-content-center"> <a type="button" class="btn btn-primary w-100">Add</a> </div> </div> </div> </body>
修改完成后,产品区域会自动填充搜索栏与底部按钮之间的所有剩余空间,当产品内容超出区域高度时,会自动出现垂直滚动条,可正常查看底部产品。
内容的提问来源于stack exchange,提问作者Hound21
相关产品推荐
相关产品推荐

