将最后一个伸缩项目放置在容器的末尾 [英] Position last flex item at the end of container
问题描述
此问题涉及具有完全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>
推荐答案
弹性项目上的自动边距效果与块流中的自动边距效果非常相似:
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-content
和align-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: auto
或margin-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屋!