最後のフレックスアイテムをコンテナの末尾に配置する 質問する

最後のフレックスアイテムをコンテナの末尾に配置する 質問する

この質問は、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-contentalign-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>

水平の例

おすすめ記事