问题描述
我有一个 div 容器,它有一个最大高度、最小高度和溢出:自动。当内部内容大于 max-height 时,会按预期出现滚动条。但是,在内容内部有一个下拉菜单,单击该下拉菜单时,菜单会展开,而不是显示在父容器之外,就像更改内部内容高度一样。
我在网上找到的唯一对我有意义的解决方案是使用相对定位将容器包装到 div 并使下拉列表绝对,但现在有一个很大的缺点,下拉保持固定在滚动上,因为它是绝对的相对于包装器而不是内容定位。是否有任何通用方法可以解决此问题或任何其他解决方案?
我没有发布任何代码,因为我不希望答案依赖于我的代码。 如果可能,我只想要一个包含这些属性的最小示例:
解决方法
为了说明我对这个问题的评论,这里有一个 MCVE:
.scroll-container {
border: 3px dashed #eee;
height: 400px;
padding: 10px;
overflow: auto;
width: 400px;
}
.content {
background-color: #f0f0f0;
height: 600px;
position: relative;
}
.dropdown {
background-color: orange;
position: absolute;
height: 300px;
width: 300px;
left: 300px;
}
<div class="scroll-container">
<div class="content">
<div class="dropdown"></div>
</div>
</div>
如您所见,使用基于 div.content
相对位置的绝对定位,橙色 div.dropdown
会产生水平溢出,这是您不想要的。要解决此问题,您需要从 position: relative
中删除 div.content
并使用 transform: translateX(300px);
而不是 left: 300px;
:
.scroll-container {
border: 3px dashed #eee;
height: 400px;
padding: 10px;
overflow: auto;
width: 400px;
}
.content {
background-color: #f0f0f0;
height: 600px;
}
.dropdown {
background-color: orange;
position: absolute;
height: 300px;
width: 300px;
transform: translateX(300px);
}
<div class="scroll-container">
<div class="content">
<div class="dropdown"></div>
</div>
</div>