Skip to content

CSS Flexbox: The Complete Guide with Examples

Flexbox is the modern one-dimensional layout model in CSS. It replaces float-based layouts with simpler, more predictable code.

The Flex Container

.container {
  display: flex;
}

This enables flex context for all direct children.

Main Axis vs Cross Axis

Flexbox works along two axes:

  • Main axis — direction set by flex-direction (default: row, left to right)
  • Cross axis — perpendicular to main axis

Key Properties

On the Parent

PropertyOptionsWhat It Does
flex-directionrow (default), column, row-reverse, column-reverseSets main axis direction
justify-contentflex-start, center, space-between, space-around, space-evenlyAligns items along main axis
align-itemsstretch, center, flex-start, flex-end, baselineAligns items along cross axis
flex-wrapnowrap, wrap, wrap-reverseAllows items to wrap to next line
gapany CSS lengthSpacing between items

On the Children

PropertyWhat It Does
flex-growHow much the item grows relative to siblings
flex-shrinkHow much the item shrinks relative to siblings
flex-basisInitial size before growing or shrinking
align-selfOverrides parent’s align-items for this item
orderChanges visual order (default 0)

Common Layouts

Navigation Bar

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

Card Grid

.grid {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
}

.card {
  flex: 1 1 300px;
}

Centered Content

.center {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
}

Holy Grail Layout

body {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

main {
  display: flex;
  flex: 1;
}

nav, aside {
  flex: 0 0 200px;
}

article {
  flex: 1;
}

Flexbox vs Grid

FlexboxCSS Grid
One-dimensional (row OR column)Two-dimensional (row AND column)
Content-drivenLayout-driven
Best for nav bars, centering, small componentsBest for page layouts, complex grids

Start with centering: See our guide on how to center a div.