这个问题涉及一个完全支持 css3 的浏览器,包括 flexbox。
我有一个 flex 容器,里面有一些元素。它们都适合 flex-start,但我希望 last .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>
最佳答案
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.
因此您可以使用 margin-top: auto
来分配其他元素和最后一个元素之间的空间。
这会将最后一个元素放在底部。
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
进行相同的水平对齐。
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>
关于css - 将最后一个 flex 元素放在容器的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33924655/