Flexbox Basics: Container and Items

What Flexbox Is For

Flexbox (the Flexible Box Layout) arranges elements along a single line - a row or a column - and automatically handles spacing, alignment and sizing between them. It replaced older hacks like floats for building navigation bars, toolbars and simple one-dimensional layouts.

The Container and Its Items

Turning on Flexbox is a two-part relationship: a parent becomes a flex container, and its direct children automatically become flex items.

.nav {
  display: flex;
}
<nav class="nav">
  <a>Home</a>
  <a>About</a>
  <a>Contact</a>
</nav>

With just display: flex, the three links already line up in a row instead of stacking, because block-level elements inside a flex container behave as flex items automatically.

Controlling the Direction

.nav {
  display: flex;
  flex-direction: row; /* default: left to right */
  /* flex-direction: column; would stack items vertically instead */
}

Spacing Items Apart

.nav {
  display: flex;
  justify-content: space-between;
  gap: 16px;
}

gap adds consistent spacing between items without needing margin tricks on the first or last child, and justify-content controls how leftover space is distributed along the row.

Why This Replaced Older Layout Hacks

Before Flexbox, evenly spacing or vertically centering elements in a row usually required floats, negative margins, or table-based layout tricks. Flexbox handles these common needs with a handful of readable properties instead.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.