如何使用flex box将一个div对齐到另一个div的底部?

3

我需要将橙色按钮与蓝色按钮底部对齐。使用当前的flex代码无法得到想要的结果。有什么建议来修复它吗?谢谢

.content {
  width: 350px;
  height: 150px;
  background-color: yellow;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.row1 {
  background-color: red;
}

.row2 {
  background-color: blue;
  height: 100px
}

.icon {
  width: 50px;
  height: 50px;
  background-color: orange;
  align-items: center;
  justify-content: center;
}
<div class="content">
  <div class="row1">
  </div>
  <div class="row2">
    <div class="icon">

    </div>
  </div>
</div>


“.icon不能使用任何flex属性,因为它的父元素没有flex属性。” - monkeyinsight
3个回答

6
您还需要在row2上设置display: flex,然后您可以在橙色元素上使用align-self: flex-end

.content {
  width: 350px;
  height: 150px;
  background-color: yellow;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.row1 {
  background-color: red;
}
.row2 {
  background-color: blue;
  display: flex;
  height: 100px
}
.icon {
  width: 50px;
  height: 50px;
  background-color: orange;
  align-self: flex-end;
}
<div class="content">
  <div class="row1"></div>
  
  <div class="row2">
    <div class="icon"></div>
  </div>
</div>


如果我不想给内容div固定高度(以像素为单位),该怎么办? - Charu Maheshwari

4

在“第二行”中,我们添加了以下CSS:

display: flex;
flex-direction: column;

这意味着如果任何对象放在底部,那么父块将设置上面的CSS,而我们需要将元素设置为底部并添加CSS "margin-top:auto;"。

.content {
  width: 350px;
  height: 150px;
  background-color: yellow;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  
}

.row1 {
  background-color: red;
}

.row2 {
  background-color: blue;
  height: 100px;
  display: flex;
  flex-direction: column;
}

.icon {
  width: 50px;
  height: 50px;
  background-color: orange;
  align-items: center;
  justify-content: center;
  margin-top: auto;
}
<div class="content">
  <div class="row1">
  </div>
  <div class="row2">
    <div class="icon">

    </div>
  </div>
</div>


1

如果不需要,您可以从代码中删除很多样式,这里是它们,请查看。我已更改 .content.row2 的样式。

.content {
    width: 350px;
    height: 150px;
    background-color: yellow;
    display: flex;
}

.row1 {
  background-color: red;
}

.row2 {
    background-color: blue;
    height: 100px;
    flex: 1;
    align-self: flex-end;
    display: flex;
    align-items: flex-end;
}

.icon {
  width: 50px;
  height: 50px;
  background-color: orange;
  align-items: center;
  justify-content: center;
}
<div class="content">
  <div class="row1">
  </div>
  <div class="row2">
    <div class="icon">

    </div>
  </div>
</div>


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