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>

相关文章

Css3如何实现鼠标移上变长特效?(图文+视频)
css3怎么实现鼠标悬停图片时缓慢变大效果?(图文+视频)
jquery如何实现点击网页回到顶部效果?(图文+视频)
css3边框阴影效果怎么做?(图文+视频)
css怎么实现圆角边框和圆形效果?(图文+视频教程)
Css3如何实现旋转移动动画特效