Skip to main content
HTML & CSS Foundations·Lesson 3 of 5

Flexbox Layout

Flexbox is a one-dimensional layout system — it arranges items in a single row or column. It excels at distributing space, aligning items, and handling dynamic content sizes.

Enabling Flexbox

Apply display: flex to a container, and its direct children become flex items:

.row {
  display: flex;
}
Ctrl+Enter
HTML
CSS
JS
Preview

By default, flex items sit in a row, don't wrap, and stretch to the container's height.

Direction and Wrapping

Control the flow direction and whether items wrap to new lines:

Ctrl+Enter
HTML
CSS
JS
Preview

When flex-wrap: wrap is set, items that don't fit on one line move to the next. Without it, items shrink to fit.

Alignment

Flexbox has two axes: the main axis (direction of flow) and the cross axis (perpendicular). Alignment properties work along these axes.

Ctrl+Enter
HTML
CSS
JS
Preview

justify-content (main axis)

Ctrl+Enter
HTML
CSS
JS
Preview
  • space-between — equal gaps between items, no gap at edges.
  • space-evenly — equal gaps everywhere, including edges.

align-items (cross axis)

Ctrl+Enter
HTML
CSS
JS
Preview
  • stretch (default) — items fill the container's cross-axis size.
  • baseline — items align by their text baselines (useful for mixed font sizes).

Individual item alignment

Override alignment for a single item with align-self:

Ctrl+Enter
HTML
CSS
JS
Preview

Gap

The gap property adds space between flex items without affecting the edges:

Ctrl+Enter
HTML
CSS
JS
Preview

This replaces the old technique of adding margins to items and removing the margin from the last one.

Flex Items: grow, shrink, basis

These three properties control how items share available space:

Ctrl+Enter
HTML
CSS
JS
Preview
/* Shorthand: flex: grow shrink basis */
.item {
  flex: 0 1 auto; /* default behavior */
}

Common patterns:

Ctrl+Enter
HTML
CSS
JS
Preview

Common Flexbox Patterns

Ctrl+Enter
HTML
CSS
JS
Preview
Ctrl+Enter
HTML
CSS
JS
Preview

Centering anything

Ctrl+Enter
HTML
CSS
JS
Preview

Input with button

Ctrl+Enter
HTML
CSS
JS
Preview

Order

Change visual order without changing HTML order. Use sparingly — it can confuse keyboard navigation:

.first-visually {
  order: -1; /* moves before items with default order: 0 */
}