将div移动到具有其他要求的父级底部

时间:2018-04-10 06:22:06

标签: html css css3 flexbox position

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

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

  • position:父级和位置的相对性:绝对的底部:0px on child不起作用,因为它缩小了hr并忽略了父div的填充。
  • Flexbox不起作用,因为我的父母已经被用作具有不同属性的弹性框,并且它也缩小了小时。

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



.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>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:1)

您可以将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>

答案 1 :(得分:0)

您可以使用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>

答案 2 :(得分:0)

添加位置:相对于父级并向孩子添加一些东西。如果您无法在父容器上使用flexbox,则此解决方案有效(尽管flexbox是更好更容易的修复)

注意:

  • 当使用position:absolute
  • 时,孩子的保证金会替换你松散的填充物
  • 要填充宽度,请使用calc(100% - (10px * 2))。这使得div达到100%,然后在每一侧减去10px的余量。这会产生一个正确填充区域的div。

&#13;
&#13;
.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));
}
&#13;
&#13;
&#13;

答案 3 :(得分:0)

由于我在父子div中使用了position relative和absolute,因此忽略了padding。因此,您必须在子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>

相关问题