CSSのflex-directionで横並び・縦並び・逆順を比較する
CSSの flex-direction はFlexboxの主軸とアイテムの配置方向を決めます。通常の横書きでは row で横に並べ、column で上下に積みます。display: flex または inline-flex を指定した親要素に適用します。
四つの方向と二つの軸を区別する
| 値 | 横書き・左から右の場合 |
|---|---|
row |
左から右(既定) |
row-reverse |
右から左 |
column |
上から下 |
column-reverse |
下から上 |
主軸はアイテムを順に並べる軸で、交差軸はそれに直交します。justify-content は主軸、align-items は交差軸で働きます。横書きで row から column に変えると、justify-content: center は横方向ではなく縦方向の中央揃えになります。CSS Flexbox · flex-direction と CSS Flexbox · Alignment を参照してください。
同じリンクを四方向に並べる例
コードを flex-direction.html として保存して開きます。四つのボックスのHTMLではいつもリンクを A、B、C の順に置き、親の方向だけを変えています。初期設定は左から右へ読む dir="ltr" です。
<!doctype html>
<html lang="ja" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Flexの四つの方向を比較</title>
<style>
body { margin: 20px; font: 16px/1.6 system-ui, sans-serif; color: #203348; }
* { box-sizing: border-box; }
h1 { font-size: 24px; }
h2 { margin: 14px 0 6px; font-size: 16px; }
.samples { max-width: 560px; }
.box { display: flex; gap: 8px; height: 132px; padding: 10px;
border: 1px solid #88a4b6; background: #eef5f8; }
.box a { display: grid; place-items: center; flex: none;
width: 48px; height: 28px; color: white; background: #176b86;
text-decoration: none; }
.box a:focus-visible { outline: 3px solid #bc5b00; outline-offset: 2px; }
.row { flex-direction: row; }
.row-reverse { flex-direction: row-reverse; }
.column { flex-direction: column; }
.column-reverse { flex-direction: column-reverse; }
</style>
</head>
<body>
<h1>flex-directionの値を比較</h1>
<div class="samples">
<section><h2>row</h2>
<div class="box row">
<a href="#result">A</a><a href="#result">B</a><a href="#result">C</a>
</div></section>
<section><h2>row-reverse</h2>
<div class="box row-reverse">
<a href="#result">A</a><a href="#result">B</a><a href="#result">C</a>
</div></section>
<section><h2>column</h2>
<div class="box column">
<a href="#result">A</a><a href="#result">B</a><a href="#result">C</a>
</div></section>
<section><h2>column-reverse</h2>
<div class="box column-reverse">
<a href="#result">A</a><a href="#result">B</a><a href="#result">C</a>
</div></section>
</div>
<p id="result">各ボックスのHTMLの順序は A → B → C です。</p>
</body>
</html>
row では A が左端、row-reverse では右端から始まります。column では上端、column-reverse では下端です。HTMLの方向を dir="rtl" に変えると、横書きでは二つの横方向の開始位置が入れ替わり、縦方向の開始位置は変わりません。確認後に ltr へ戻します。 縦書きの writing-mode では row は縦のインライン軸に沿います。
画面幅に応じてツールバーを縦にする
狭い画面でツールバーを縦に積む場合は、メディアクエリーで切り替え、高さは内容に任せます。最初のボックスの row クラスだけを toolbar に置き換え、style の最後に以下を加えます。display: flex を指定する box クラスは残します。
.toolbar {
flex-direction: row;
height: auto;
}
@media (max-width: 640px) {
.toolbar {
flex-direction: column;
}
}
ビューポートの幅が640px以下ならリンクが縦に、より広ければ横に並びます。比較後は追加した規則を削除して row を戻します。横方向を保ちながら、収まらない項目を次の行に送る場合は flex-wrap を設定します。
見た目とTab移動の順序を確認する
Tabで二つ目のボックスへ移動します。見た目は左から C、B、A の順ですが、フォーカスは右端の A から B、C へ進みます。逆方向の値は見た目を変えるためのものです。記入順が重要なフォームや手順では、HTML上でリンクや入力項目の順序を決めてください。CSS Flexbox · Reordering and Accessibility を参照してください。




