← Learning Hub
Beginner

Flexbox Layout

Flexbox arranges items in a row or a column and shares out the space between them. Set display: flex on the parent, and its children become flex items.

  • justify-content spreads items along the main direction (for example space-between or center).
  • align-items lines them up across it (for example center).
  • gap adds space between items.
  • flex-wrap: wrap lets items move to a new line on small screens.

Before flexbox, putting items side by side or centering something vertically was famously hard. Flexbox solved it. You'll use it for navigation bars, rows of product cards, buttons with icons, forms, footers - almost every component on a modern site.

The idea: the parent (container) controls the layout of its children. You tell the container which direction to arrange items in (flex-direction: row or column), how to spread them, and how to align them. The children then fit themselves into the available space. For full-page grids with rows and columns, CSS Grid is the partner tool.

Example
<!DOCTYPE html>
<html>
  <head>
    <style>
      .nav { display: flex; justify-content: space-between; align-items: center;
             background: #1e293b; color: white; padding: 12px 16px; }
      .links { display: flex; gap: 16px; }
      .cards { display: flex; flex-wrap: wrap; gap: 12px; padding: 16px; }
      .cards div { flex: 1 1 140px; background: #e0e7ff; padding: 20px; border-radius: 8px; text-align: center; }
    </style>
  </head>
  <body>
    <div class="nav"><b>MyShop</b><div class="links"><span>Home</span><span>Deals</span><span>Cart</span></div></div>
    <div class="cards"><div>One</div><div>Two</div><div>Three</div><div>Four</div></div>
  </body>
</html>
▶ Try it yourself
Make the preview narrower or wider: the cards wrap onto new lines because of flex-wrap and flex: 1 1 140px.
Key points
  • display: flex on the parent arranges its children in a row or column.
  • justify-content spreads along the row; align-items aligns across it.
  • gap adds space; flex-wrap: wrap lets items move to the next line.

📝 Test yourself

1. Where do you write display: flex?
2. Which property adds space between flex items?
3. Fill in the value that lets items move to a new line:
flex-wrap: ;