【问题标题】:Stretch div to the top of other variable height div without using absolute positioning在不使用绝对定位的情况下将 div 拉伸到其他可变高度 div 的顶部
【发布时间】:2019-09-04 06:28:21
【问题描述】:
我有两个垂直堆叠的 div。单击按钮时,我试图将下 div 拉伸到上 div 的顶部。这在底部 div 使用绝对定位时效果很好,根据需要更新下部 div 的top 属性。
当顶部 div 是可变高度时,问题就出现了。我希望较低的 div 在不拉伸时坐在顶部 div 的底部。如何更新下面的代码,使底部 div 始终位于顶部 div 下方,即使它的高度发生变化?
Example using absolute positioning
【问题讨论】:
-
如果您不介意下 div 的底部延伸到包装器的底部(也许调整包装器的高度?)您可以应用 position: absolute; 和 expanded 类。这样,它的顶部按预期工作,同时仍然响应上 div 高度。 Here's the example
标签:
javascript
html
css
transform
【解决方案1】:
对于这种情况,您应该避免使用position: absolute,因为使元素停止相互影响。相反,我建议您对这两个元素使用 flexbox 组合宽度 min-width 和 max-width 。
如果您的组件始终具有固定高度(在您的示例中为 300 像素),则内容可能会溢出容器。
我稍微了解一下设计上下文会有所帮助,所以希望这个解决方案对你有用。
document.querySelector('.toggle').addEventListener('click', function() {
document.querySelector('.wrapper').classList.toggle('expanded');
});
body {
margin: 10rem;
}
div {
width: 12rem;
}
.wrapper {
display: flex;
flex-flow: column nowrap;
align-items: stretch;
height: 300px;
position: relative;
}
.stationary {
min-height: 50%;
max-height: 100%;
transition: min-height 1s, max-height 1s;
background: red;
overflow: auto;
}
.expanded .stationary {
max-height: 0;
min-height: 0%;
}
.expanding {
flex: auto;
bottom: 0;
height: 100%;
max-height: auto;
background: blue;
transition: max-height 1s;
}
.expanded .expanding {
max-height: 100%;
transition: max-height 1s;
}
<button class="toggle">Toggle</button>
<div class="wrapper">
<div class="stationary">
Random text that makes this a variable height div....
Random text that makes this a variable height div....
Random text that makes this a variable height div....
Random text that makes this a variable height div....
Random text that makes this a variable height div....
Random text that makes this a variable height div....
</div>
<div class="expanding">
Random text that makes this a variable height div....
Random text that makes this a variable height div....
</div>
</div>
【解决方案2】:
也许其中一种选择不是展开blue div,而是折叠红色div。
这是一种方法。
https://codepen.io/anon/pen/yrzBja
诀窍是让包装器的背景变成蓝色。
唯一的问题是max-height 需要设置为任意值(在我的示例中为100%),因此转换看起来有点延迟。
我希望您能从中得到一些启发,以进一步改进您的解决方案。