HTML•Flexbox レイアウト
CSS Flexbox:flex-direction、justify-content、align-items
Flexbox は主軸(justify-content)と交差軸(align-items)に沿って余白と配置を動的に配分します。
構文
.container { display: flex; justify-content: space-between; align-items: center; }
パラメータと値
この構文の主な構成要素と指定可能な値:
| パラメータ | 型 | 説明 |
|---|---|---|
| justify-content | Property | 主軸に沿ってアイテムを整列します(flex-start, center, space-between)。 |
| align-items | Property | 交差軸に沿ってアイテムを整列します(center, stretch)。 |
そのまま実行できるコード例
Compilra で実行可能HTML をローカルにインストールせずに、この動作する完全なコード例を直接実行できます:
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; padding: 20px; }
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
background: #0f172a;
color: white;
padding: 12px 20px;
border-radius: 8px;
}
.nav-links { display: flex; gap: 15px; }
.nav-links a { color: #94a3b8; text-decoration: none; font-size: 14px; }
</style>
</head>
<body>
<h2>CSS Flexbox Navigation Bar</h2>
<nav class="navbar">
<strong>Compilra</strong>
<div class="nav-links">
<a href="#">Compiler</a>
<a href="#">Tutorials</a>
<a href="#">Docs</a>
</div>
</nav>
</body>
</html>期待される出力:
[Rendered Flexbox Navigation Bar: Left-Aligned Brand, Right-Aligned Navigation Links with Gaps]
動作のしくみ: ステップ解説
- 6〜13行目: display: flex と justify-content: space-between により、ブランドを左端、リンクを右端に配置します。
- 14行目: gap: 15px がリンク間にすっきりとした余白を作ります。
重要ポイント
- display: flex は要素をフレックスコンテナに変換します。
- gap を使うと margin ハックなしでアイテム間の間隔を設定できます。
よくある間違い: gap プロパティの代わりに子要素へ margin ハックを使う
モダンな CSS ではフレックスコンテナに直接 gap: 1rem を指定でき、:last-child でのマージン調整が不要になります。
❌ 誤り
.item { margin-right: 10px; } .item:last-child { margin-right: 0; }✅ 正しい例
.container { display: flex; gap: 10px; }関連するHTMLチュートリアルとコンパイラ
HTML 表形式データマトリクス:テーブルセマンティクスを用いた構造化レイアウト
列揃えと指標フォーマットを備えたセマンティックなテーブル要素(<table>, <thead>, <tbody>, <tfoot>, <tr>, <th>, <td>)で表形式データマトリクスを構築します。
CSS Grid レイアウト:grid-template-columns とレスポンシブグリッド
CSS Grid と repeat(auto-fit, minmax(200px, 1fr)) を使って 2 次元レイアウトを習得しましょう。
DOM 操作:querySelector、textContent、innerHTML
document.querySelector と textContent を使って HTML 要素を選択・操作しましょう。
HTML オンラインコンパイラ
Compilra IDE で開く