如何创建两个柔性容器,一个随着内容物的增加而增加其高度,另一个则不增加?



我希望创建两个彼此相邻的容器,占据整个宽度(通过flex分布(并具有相同的高度。左边的应该随着其内容而增加其高度,右边的应该始终与左边的高度完全相同,必要时滚动其内容。

结构如下所示。目前,右列会增长左列(和父容器(,这不应该发生。显然max-height在这里没有任何影响,因为引用是父div。我怎样才能做到这一点?

.container { 
display: flex;
}
.col1 { 
flex: 1;
background: #999;
}
.col2 { 
flex: 2;
background: #F00;
max-height: 100%; /* max-height should be height of left column */
overflow: auto;
}
<div class="container">
<div class="col1">
this<br>
div<br>
should<br>
grow<br>
based<br>
on<br>
content
</div>
<div class="col2">
this<br>
div<br>
should<br>
never<br>
exceed<br>
the height<br>
defined by the left one<br>
(which happens with this row)<br>
it should scroll instead
</div>
</div>

这是因为弹性框的大小始终取决于其自己的内部内容:在这种情况下,您想要的是将.col2中的所有内容从文档流中取出,这样它就不会影响整个弹性框的大小。

为此,您需要将.col2的内容包装在绝对位于.col2内的包装器元素中:

.container { 
display: flex;
}
.col1 { 
flex: 1;
background: #999;
}
.col2 { 
flex: 2;
background: #F00;
position: relative;
}
.col2 .wrapper {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
overflow: auto;
}
<div class="container">
<div class="col1">
this<br>
div<br>
should<br>
grow<br>
based<br>
on<br>
content
</div>
<div class="col2">
<div class="wrapper">
this<br>
div<br>
should<br>
never<br>
exceed<br>
the height<br>
defined by the left one<br>
(which happens with this row)<br>
it should scroll instead
</div>
</div>
</div>

e dit :另一个类似的答案在我的之前发布过,我认为这里不能使用另一种方法


您将需要一个额外的包装器来将内容从流中删除。 位置:相对/绝对 将在需要时共同设置滚动条,而无需考虑主容器的大小。

可能的例子:

.container {
display: flex;
}
.col1 {
flex: 1;
background: #999;
}
.col2 {
flex: 2;
background: #F00;
position: relative;
}
.col2>div {
position: absolute;
top: 0;
left: 0;
width: 100%;
max-height: 100%;
/* max-height should be height of left column */
overflow: auto;
}
<div class="container">
<div class="col1">
this<br> div
<br> should
<br> grow
<br> based
<br> on
<br> content
</div>
<div class="col2">
<div class="buffer">this<br> div
<br> should
<br> never
<br> exceed
<br> the height<br> defined by the left one<br> (which happens with this row)<br> it should scroll instead
</div>
</div>
</div>

最新更新