HTML:CSS Flexbox: flex-direction, justify-content, and align-items
HTML•Flexbox Layout

CSS Flexbox: flex-direction, justify-content, and align-items

Flexbox distributes space along a main axis (justify-content) and cross axis (align-items) dynamically.

Syntax

.container { display: flex; justify-content: space-between; align-items: center; }

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
justify-contentPropertyAligns items along main axis (flex-start, center, space-between).
align-itemsPropertyAligns items along cross axis (center, stretch).

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing HTML locally:

<!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>
Expected Output:
[Rendered Flexbox Navigation Bar: Left-Aligned Brand, Right-Aligned Navigation Links with Gaps]

How It Works: Step-by-Step

  • Lines 6-13: display: flex with justify-content: space-between pushes brand left and links right.
  • Line 14: gap: 15px provides clean spacing between links.

Key Concepts

  • display: flex turns the element into a flex container.
  • gap sets gutters between items without needing margin hacks.

Common Mistake: Using margin hacks on children instead of the gap property

Modern CSS supports gap: 1rem directly on flex containers, avoiding :last-child margin resets.

❌ Incorrect
.item { margin-right: 10px; } .item:last-child { margin-right: 0; }
✅ Correct
.container { display: flex; gap: 10px; }

Related HTML Tutorials & Compiler

Run and test HTML on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

HTML Online Compiler