height:fit-content父容器下子元素100%高度滚动失效问题求助
实现wrapper内main容器的垂直滚动解决方案
问题根源在于height: fit-content使wrapper高度完全由子元素撑开,main的calc(100% - 20px)因父元素无明确高度基准而失效,无法触发滚动。改用Flexbox布局可完美解决这个矛盾,既保留wrapper自适应内容高度的特性,又能让main在内容超出时出现滚动:
修改后的CSS代码
.wrapper { max-height: 200px; display: flex; flex-direction: column; border: 2px solid red; } .header{ height: 20px; background: #ccc; /* 可选:方便区分header区域 */ } .main{ flex: 1; /* 自动填充wrapper的剩余空间 */ overflow-y: auto; } .content{ height: 1000px; background: #0f0; }
HTML结构(无需修改)
<div class='wrapper'> <div class='header'></div> <div class='main'> <div class='content'></div> </div> </div>
效果说明
- 当内容总高度小于200px时,wrapper会自适应内容高度,等同于原来
height: fit-content的效果; - 当内容总高度超过200px时,wrapper被
max-height限制在200px,header固定占20px,剩余空间全部分配给main,content超出main高度时自动触发垂直滚动。
内容的提问来源于stack exchange,提问作者kan
相关产品推荐
相关产品推荐

