首页 > 解决方案 > 位置绝对但相对

问题描述

目前我使用这个 CSS 将一个 div (.child_bottom) 放置在其父级的底部,并在其上方放置另一个 div (.child),因为我知道 (.child_bottom) 的高度。

高度可变的父级。

.parent
{
  position:relative;
}

.child
{
  position:absolute;
  bottom:250px;
}

.child_bottom
{
  position:absolute;
  bottom:0;
  height:250px;
}
<div class="parent">

  <div class="child"></div>
  
  <div class="child_bottom"></div>

</div>

但是我想用.child_bottom的可变高度获得同样的东西,怎么办?

预先感谢您的帮助。

标签: htmlcsspositionabsolute

解决方案


使用 flex 将允许您删除所有绝对定位:

.parent {
  height: 400px;
  outline: 1px solid blue;
  
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
}

.child {
  background: green;
}

.child_bottom {
  background: orange;
  height: 250px;
}
<div class="parent">

  <div class="child">CHILD</div>

  <div class="child_bottom">CHILD_BOTTOM</div>

</div>

如果您之前确实希望添加内容.child,请删除justify-content并制作此内容flex: 1

.parent {
  display: flex;
  flex-direction: column;
  /* justify-content: flex-end; */
  height: 400px;
  outline: 1px solid blue;
}

.child {
  background: green;
}

.child_bottom {
  background: orange;
  height: 250px;
}

.other_content {
  background: yellow;
  flex: 1;
}
<div class="parent">

  <div class="other_content">
    OTHER_CONTENT (Fills the space)
  </div>

  <div class="child">CHILD</div>

  <div class="child_bottom">CHILD_BOTTOM</div>

</div>


推荐阅读