微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

css – 将最后一个弹性项目放在容器的末尾

此问题涉及具有完整css3支持的浏览器,包括flexBox

我有一个Flex容器,里面有一些物品。他们都有理由进行flex-start,但我希望最后一个.end项被证明是flex-end。有没有一个很好的方法来做到这一点,而无需修改HTML,也没有求助于绝对定位?

.container {
  display: flex;
  flex-direction: column;
  outline: 1px solid green;
  min-height: 400px;
  width: 100px;
  justify-content: flex-start;
}
p {
  height: 50px;
  background-color: blue;
  margin: 5px;
}
<div class="container">
  <p></p>
  <p></p>
  <p></p>
  <p class="end"></p>
</div>

解决方法

07000

Auto margins on flex items have an effect very similar to auto margins in block flow:

  • During calculations of flex bases and flexible lengths,auto margins are treated as 0.

  • Prior to alignment via justify-content and align-self,any positive free space is distributed to auto margins in that dimension.

因此,您可以使用margin-top:auto来分配其他元素和最后一个元素之间的空间。这会将元素定位在底部

.end {
  margin-top: auto;
}

您还可以避免使用类并使用:last-of-type / last-child伪类。

p:last-of-type {
  margin-top: auto;
}
.container {
  display: flex;
  flex-direction: column;
  outline: 1px solid green;
  min-height: 400px;
  width: 100px;
  justify-content: flex-start;
}
p {
  height: 50px;
  background-color: blue;
  margin: 5px;
}
.end {
  margin-top: auto;
}
<div class="container">
  <p></p>
  <p></p>
  <p></p>
  <p class="end"></p>
</div>

原文地址:https://www.jb51.cc/css/217958.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。