对于这个问题我真的很抱歉,因为我在这里已经看到了很多类似的问题,但我仍然想不明白.
我想创建一个带有display
元素控件的overlay
元素,其中控件垂直堆叠并与显示屏的右侧和底部对齐.存在一个包含一些控件的固定大小元素buttons
,然后是一个动态大小的元素info
,该元素仅在显示器的某些部分处于活动状态时弹出.info
始终包含一个可自行关闭的按钮,以及一些动态高度的信息.我希望info
容器始终缩小到其内容.然而,如果内容的高度太大,以至于包含的info
元素会比overlay
容器的剩余垂直空间高,那么我希望内容是可滚动的.
我以为我只需要使用一个Flex容器和overflow-y
个属性,但这似乎并没有解决这个问题.溢出似乎只有在父容器有一些明确的高度时才会触发,但在我的例子中,父容器是动态的,这意味着它应该增长到定义的高度,然后停止,而内容变得可滚动.
这是我迄今为止的try :
const info = document.querySelector(".info");
const content = document.querySelector(".content");
document.querySelector("#open-info").addEventListener("click", () => {
info.style.display = "flex";
});
document.querySelector("#close-info").addEventListener("click", () => {
info.style.display = "none";
});
document.querySelector("#increase-height").addEventListener("click", () => {
content.style.height = `${content.clientHeight + 30}px`;
});
document.querySelector("#decrease-height").addEventListener("click", () => {
content.style.height = `${content.clientHeight - 30}px`;
});
.display {
position: relative;
width: 400px;
height: 300px;
background-color: gray;
}
.overlay {
position: absolute;
display: flex;
width: 100%;
height: 100%;
top: 0;
left: 0;
flex-direction: column;
justify-content: flex-end;
align-items: flex-end;
}
.info {
display: flex;
flex-direction: column;
justify-content: flex-end;
align-items: flex-end;
flex-shrink: 0;
background-color: orange;
padding: 10px;
max-height: 230px;
/* overflow works, but fixed size is undesirable, as the remaining space in main-axis direction should be used up */
/* max-height: 100%; overflow doesn't work, as it refers to parent's height, not to remaining available space in main-axis direction*/
}
.info-content-wrapper {
padding: 5px;
overflow-x: hidden;
overflow-y: auto;
}
.content {
width: 80px;
height: 150px;
background-color: yellow;
}
.controls {
background-color: lightblue;
padding: 5px;
flex: 0 0 auto;
}
<div class="display">
<div class="overlay">
<div class="info">
<button id="close-info">Close</button>
<div class="info-content-wrapper">
<div class="content"></div>
</div>
</div>
<div class="controls">
<button id="open-info">Open info</button>
<button id="increase-height">+</button>
<button id="decrease-height">-</button>
</div>
</div>
</div>
在示例中,您可以使用按钮隐藏/显示信息,以及增加/减少内容高度.我在.info
上使用了固定的max-height: 230px
来演示它应该如何工作.然而,它不应该使用固定的max-height
,而应该使用柔性容器的剩余垂直空间.但当我使用max-height: 100%
时,它将(根据定义)指的是父Flex容器的总高度.如果我将其进一步嵌套(比如在内部HTML .info
周围引入包装器)并将该元素的max-height
设置为100%
,它仍然不起作用.
我觉得答案应该非常简单,但我似乎无法通过灵活布局而不诉诸calc
的一些变通方法来找到解决方案.我对此感到非常愚蠢,并且很高兴得到一些帮助!