将最后一个伸缩项目放置在容器的末尾 [英] Position last flex item at the end of container

查看:58
本文介绍了将最后一个伸缩项目放置在容器的末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题涉及具有完全css3支持(包括flexbox)的浏览器.

This question concerns a browser with full css3 support including flexbox.

我有一个Flex容器,里面装有一些物品.它们都可以进行弹性启动,但是我希望 last .end项目可以进行弹性结束.有没有一种好的方法,而无需修改HTML且不求助于绝对定位?

I have a flex container with some items in it. They are all justified to flex-start but I want the last .end item to be justified to flex-end. Is there a good way to do this without modifying the HTML and without resorting to absolute positioning?

.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>

推荐答案

灵活框布局模块-8.1.与自动页边距对齐

弹性项目上的自动边距效果与块流中的自动边距效果非常相似:

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

  • 在计算伸缩度和柔性长度期间,自动边距被视为0.

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

在通过justify-contentalign-self对齐之前,任何正的自由空间都会分配给该维度中的自动边距.

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

因此,您可以使用margin-top: auto在其他元素和最后一个元素之间分配空间.

Therefore you could use margin-top: auto to distribute the space between the other elements and the last element.

这会将最后一个元素放在底部.

This will position the last element at the bottom.

p:last-of-type {
  margin-top: auto;
}

.container {
  display: flex;
  flex-direction: column;
  border: 1px solid #000;
  min-height: 200px;
  width: 100px;
}
p {
  height: 30px;
  background-color: blue;
  margin: 5px;
}
p:last-of-type {
  margin-top: auto;
}

<div class="container">
  <p></p>
  <p></p>
  <p></p>
</div>

同样,您也可以使用margin-left: automargin-right: auto水平对齐.

Likewise, you can also use margin-left: auto or margin-right: auto for the same alignment horizontally.

p:last-of-type {
  margin-left: auto;
}

.container {
  display: flex;
  width: 100%;
  border: 1px solid #000;
}
p {
  height: 50px;
  width: 50px;
  background-color: blue;
  margin: 5px;
}
p:last-of-type {
  margin-left: auto;
}

<div class="container">
  <p></p>
  <p></p>
  <p></p>
  <p></p>
</div>

这篇关于将最后一个伸缩项目放置在容器的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆