この質問は、flexbox を含む完全な CSS3 サポートを備えたブラウザに関するものです。
いくつかのアイテムが入ったフレックス コンテナーがあります。それらはすべて 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>
ベストアンサー1
フレキシブル ボックス レイアウト モジュール - 8.1. 自動マージンによる配置
フレックス アイテムの自動マージンは、ブロック フローの自動マージンと非常によく似た効果があります。
フレックス ベースとフレックス レングスの計算中、自動マージンは 0 として扱われます。
および による位置合わせの前に
justify-content
、align-self
正の空きスペースはその次元の自動マージンに分配されます。
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>