将 div 移动到父级的底部,并提出其他要求



如何将子div 拼凑到父div 的底部?该解决方案需要保持 hr 宽度满,保持父div 的填充工作并保持文本向右对齐。

为什么以前的答案不起作用:

    位置:
  • 相对于父级和位置:绝对与底部:0px 在子级上不起作用,因为它缩小了 HR 并忽略了父div 的填充。
  • 弹性框
  • 不起作用,因为我的父母已经被用作具有不同属性的弹性框,并且它还缩短了小时数。

当然会查看包含定位或弹性框的答案,但我已经尝试了我所知道的,但没有找到一个好的解决方案。

.parent {
  width: 500px;
  height: 250px;
  background-color: gray;
  padding: 10px;
}
.child {
  height: 50px;
  text-align: right;
}
<div class="parent">
  <div class="child">
    <hr>
    <label>I am Batman</label>
  </div>
</div>

您可以为元素提供margin-top: autowidth: 100%

.parent {
  width: 500px;
  height: 250px;
  background-color: gray;
  padding: 10px;
  display: flex;
}
.child {
  height: 50px;
  text-align: right;
  margin-top: auto;
  width: 100%;
}
<div class="parent">
  <div class="child">
    <hr>
    <label>I am Batman</label>
  </div>
</div>

添加位置:相对于父级,并为子项添加一些内容。如果您无法在父容器上使用弹性框,则此解决方案有效(尽管弹性框是一个更好、更容易的修复(

笔记:

  • 子项边距替换使用时松散的填充 位置:绝对
  • 要填充宽度,请使用 calc(100% - (10px*2((。这使得div 为 100%,然后在每边减去 10px 的边距。这将导致一个正确填充该区域的div。

.parent {
  width: 1000px;
  height: 500px;
  background-color: gray;
  padding: 10px;
  position: relative;
}
.child {
  height: 50px;
  background-color: orange;
  text-align: right;
  position: absolute;
  bottom: 0px;
  right: 0px;
  margin: 10px;
  width: calc(100% - (10px*2));
}

由于我在父子div 中使用了位置相对和绝对,因此它忽略了填充。因此,您必须在子div中设置底部才能根据需要显示它。

.parent {
  width: 500px;
  height: 250px;
  background-color: gray;
  padding: 10px;
  position:relative;
}
.child {
  width:calc(100% - (10px*2));
  height: 50px;
  text-align: right;
  position:absolute;
  bottom:10px;
}
<div class="parent">
  <div class="child">
    <hr>
    <label>I am Batman</label>
  </div>
</div>

您可以使用

align-self: flex-end

.parent {
  width: 500px;
  height: 250px;
  background-color: gray;
  padding: 10px;
  display: flex;
}
.child {
  flex: 1; /* mimics "width: 100%" */
  align-self: flex-end; /* affects horizontal alignment, places itself at the bottom of the parent element */
  height: 50px;
  text-align: right;
}
<div class="parent">
  <div class="child">
    <hr>
    <label>I am Batman</label>
  </div>
</div>

相关内容

最新更新