在深层嵌套的灵活容器中滚动
Posted
技术标签:
【中文标题】在深层嵌套的灵活容器中滚动【英文标题】:Scroll in deep nested flexible containers 【发布时间】:2021-07-17 21:07:08 【问题描述】:在这个代码示例中,我实现了灵活的滚动容器,采用深度灵活的嵌套结构。
https://jsfiddle.net/n3vctjr4/
.container
width: 300px;
height: 500px;
border: 1px solid black;
display: flex;
flex-direction: column;
.static
padding: 1rem;
background: red;
.flexible
display: flex;
flex-direction: column;
min-height: 0;
.flexible div
display:flex;
flex-direction: column;
min-height: 0;
.overflow
overflow: auto;
<!-- Container element -->
<div class="container">
<!-- Not flexible container -->
<div class="static">HEADER</div>
<!-- Flexible container -->
<div class="flexible">
<!-- Nested containers -->
<div class="nesting-1">
<div class="nesting-2">
<div class="nesting-3">
<div class="nesting-4">
<div class="nesting-5">
<!-- Scrollable container -->
<div class="nesting-6 overflow">
<br> <br> <br> <br> <br> <br> <br> <br> <br>
scroll here
<br> <br> <br> <br> <br> <br> <br> <br> <br>
<br> <br> <br> <br> <br> <br> <br> <br> <br>
end
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Not flexible container -->
<div class="static">FOOTER</div>
</div>
除了将 min-height 和 display:flex 放在“灵活”层次结构中的每个 div 上一直到顶部元素之外,还有其他更好/更简单的解决方案吗?
【问题讨论】:
【参考方案1】:我们可以摆脱display: flex
,因为没有水平对齐的元素。所以我们的任务就是创建垂直对齐的元素。我们知道div
默认有display: block
,所以让我们使用它:
*, html, body
margin: 0;
box-sizing: border-box;
height: 100%;
.container
width: 300px;
height: 500px;
border: 1px solid black;
.static
padding: 1rem;
height: 10%;
background: red;
.middle
height: 80%;
.overflow
overflow: auto;
<div class="container">
<div class="static">HEADER</div>
<div class="middle">
<div class="nesting-1">
<div class="nesting-2">
<div class="nesting-3">
<div class="nesting-4">
<div class="nesting-5">
<div class="nesting-6 overflow">
<br> <br> <br> <br> <br> <br> <br> <br> <br>
scroll here
<br> <br> <br> <br> <br> <br> <br> <br> <br>
<br> <br> <br> <br> <br> <br> <br> <br> <br>
end
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="static">FOOTER</div>
</div>
【讨论】:
以上是关于在深层嵌套的灵活容器中滚动的主要内容,如果未能解决你的问题,请参考以下文章