将最后一个 flex 项目放置在容器的末尾 [英] Position last flex item at the end of container
问题描述
此问题涉及具有完整 css3 支持(包括 flexbox)的浏览器.
我有一个 flex 容器,里面有一些项目.它们都适合 flex-start,但我希望 last .end
项目适合 flex-end.有没有不修改 HTML 且不诉诸绝对定位的好方法?
.container {显示:弹性;弹性方向:列;轮廓:1px纯绿色;最小高度:400px;宽度:100px;justify-content: flex-start;}p{高度:50px;背景颜色:蓝色;边距:5px;}
<p></p><p></p><p></p><p class="end"></p>
同样,您也可以使用
margin-left: auto
或margin-right: auto
来实现相同的水平对齐.p:last-of-type {左边距:自动;}
.container {显示:弹性;宽度:100%;边框:1px 实心 #000;}p{高度:50px;宽度:50px;背景颜色:蓝色;边距:5px;}p:last-of-type {左边距:自动;}
<p></p><p></p><p></p><p></p>This question concerns a browser with full css3 support including flexbox.
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>
解决方案Flexible Box Layout Module - 8.1. Aligning with auto margins
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
andalign-self
, any positive free space is distributed to auto margins in that dimension.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>
Likewise, you can also use
margin-left: auto
ormargin-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>
这篇关于将最后一个 flex 项目放置在容器的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!