問題5: flex-directionの影響

問題

flex-direction: columnに変更したら、justify-contentalign-itemsが意図と逆の動作をするようになりました。なぜでしょうか?

HTML

<div class="container">
  <div class="item">Item 1</div>
  <div class="item">Item 2</div>
  <div class="item">Item 3</div>
</div>

CSS(row方向)

.container {
  display: flex;
  flex-direction: row;  /* 横方向 */
  justify-content: center;  /* 横方向の中央寄せ */
  align-items: center;      /* 縦方向の中央寄せ */
  height: 200px;
  background-color: #e8e8e8;
}

.item {
  padding: 10px 20px;
  margin: 5px;
  background-color: #FF6B6B;
  color: white;
}

row方向の結果

Item 1
Item 2
Item 3

CSS(column方向に変更)

.container {
  display: flex;
  flex-direction: column;  /* 縦方向に変更 */
  justify-content: center;  /* 期待:横中央 → 実際:縦中央 */
  align-items: center;      /* 期待:縦中央 → 実際:横中央 */
  height: 200px;
  background-color: #e8e8e8;
}

column方向の結果

Item 1
Item 2
Item 3

※ justify-contentとalign-itemsの効果が入れ替わったように見えます

🔧 実際に試してみよう(リアルタイム更新)

上部でHTMLまたはCSSタブを選択して編集すると、下部の結果エリアがリアルタイムで更新されます。
CSSの flex-directionrowcolumn に変更して、違いを確認してみましょう。

📺 ライブプレビュー
更新中

ヒント

クリックしてヒントを表示

justify-contentは常に主軸(main axis)方向の配置を制御します。

align-itemsは常に交差軸(cross axis)方向の配置を制御します。

flex-directionを変更すると、主軸と交差軸の方向が変わります。

解答

クリックして解答を表示

問題の原因

flex-directionを変更すると、主軸と交差軸の方向が入れ替わるため、justify-contentalign-itemsが制御する方向も変わります。

軸の変化

flex-direction 主軸(main axis) 交差軸(cross axis)
row 横方向(左→右) 縦方向(上→下)
row-reverse 横方向(右→左) 縦方向(上→下)
column 縦方向(上→下) 横方向(左→右)
column-reverse 縦方向(下→上) 横方向(左→右)

プロパティと軸の関係

flex-direction: row の場合

  • justify-content横方向(主軸)
  • align-items縦方向(交差軸)
主軸 →
交差軸 ↓

flex-direction: column の場合

  • justify-content縦方向(主軸)
  • align-items横方向(交差軸)
主軸 ↓
交差軸 →

実用例:完全な中央配置

flex-direction: row での中央配置

.container-row {
  display: flex;
  flex-direction: row;
  justify-content: center;  /* 横中央 */
  align-items: center;      /* 縦中央 */
  height: 200px;
}

flex-direction: column での中央配置

.container-column {
  display: flex;
  flex-direction: column;
  justify-content: center;  /* 縦中央 */
  align-items: center;      /* 横中央 */
  height: 200px;
}

よくある使用パターン

縦並びのナビゲーション

.sidebar-nav {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;  /* 上寄せ */
  align-items: stretch;          /* 横幅いっぱい */
}

カードの縦積み

.card-stack {
  display: flex;
  flex-direction: column;
  justify-content: space-between;  /* 均等配置 */
  align-items: center;              /* 横中央 */
  min-height: 100vh;
}

覚えておくポイント

  • justify-contentは常に主軸方向を制御(方向に依存しない)
  • align-itemsは常に交差軸方向を制御(方向に依存しない)
  • flex-directionを変更すると主軸と交差軸が入れ替わる
  • 「横中央・縦中央」ではなく「主軸中央・交差軸中央」で考える
  • デバッグ時は、まずflex-directionの値を確認する