不使用绝对定位将div拉伸到其他高度不同的div的顶部

5
我有两个垂直堆叠的div。当点击按钮时,我试图将底部div拉伸到上部div的顶部。当底部div使用绝对定位时,更新需要的下部div的“top”属性可行。
问题出在当上部div的高度是可变的情况下。我想让下部div在未被拉伸时坐落在上部div的底部。如何更新下面的代码,以使底部div始终位于上部div下方,即使其高度发生变化? 使用绝对定位示例

如果您不介意较低的div底部延伸到包装器的底部(也许调整包装器的高度?),则可以使用expanded类应用position: absolute;。这样,它的顶部部分就像预期的那样工作,同时仍然对上面的div高度进行响应。这是一个例子 - Kacper Dębowski
2个回答

1
对于这种情况,您应该避免使用position: absolute,因为它会使元素停止相互影响。相反,我建议您使用 flexbox 以及宽度、最小宽度和最大宽度来组合两个元素。 如果您的组件始终具有固定高度(例如您的示例中的300px),则可能会发生内容溢出容器的情况。 更多的设计背景可能会有所帮助,希望这些解决方案对您有用。

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>


1
也许其中一个选项不是扩展 blue div,而是折叠红色的 div。 以下是一种实现方法。

https://codepen.io/anon/pen/yrzBja

技巧是使包装器的背景变为蓝色。

唯一的问题是max-height需要设置为一些任意值(在我的例子中为100%),这样过渡看起来有点延迟。

我希望您从中得到一些灵感,进一步改善您的解决方案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接