已设置overflow:auto的子容器内元素仍溢出父容器问题求助
问题根源
你给.box-container设置的height: 100%是相对于父级.container的总高度,但.container内还有h2、h3、底部h5这些同级元素占用了固定高度,两者相加总高度超过了.container的100%视口高度,自然会出现溢出。
解决方案
用flex纵向布局自动分配剩余空间即可,只需修改两处CSS配置:
- 给父容器
.container开启纵向flex布局 - 把
.box-container的固定高度height: 100%替换为flex: 1,让它自动填充剩余可用高度
修改后的完整CSS代码如下:
* { box-sizing: border-box; } html, body { margin: 0; height: 100%; font-family: Arial, sans-serif; } .container { position: fixed; top: 0; right: 0; height: 100%; width: 30%; background-color: #f9f9f9; padding: 20px 30px; /* 新增以下两行 */ display: flex; flex-direction: column; } .box-container { display: flex; justify-content: space-between; flex-wrap: wrap; /* 把height:100%替换为flex:1 */ flex: 1; overflow-y: auto; /* 可选:给上下加一点间距避免和标题贴太紧 */ margin: 10px 0; } .box { display: flex; justify-content: center; align-items: center; height: 150px; width: 49%; background-color: #FFDAC7; margin-bottom: 5px; font-size: 32px; }
修改后.box-container会自动占据标题和底部按钮之外的所有剩余高度,超出的子元素会在容器内部滚动,不会再溢出父容器,也不会挤压其他同级元素的显示位置。
内容的提问来源于stack exchange,提问作者KentAgent
相关产品推荐
相关产品推荐

