·5 min read

CSS Flexbox Cheat Sheet: The Only Guide You Need

CSSFlexboxLayout

Flexbox is the most-used CSS layout system — and for good reason. It handles alignment, spacing, and ordering with minimal code. Here's everything you need.

The Two Axes

Flexbox has a main axis (direction items flow) and a cross axis (perpendicular). Understanding this is key to every property below.

css
.container {
  display: flex;
  flex-direction: row; /* main axis = horizontal (default) */
}

Change flex-direction to column and the main axis becomes vertical.

justify-content — Main Axis Alignment

Controls how items are distributed along the main axis:

css
justify-content: flex-start;    /* Pack items to the start */
justify-content: center;        /* Center items */
justify-content: flex-end;      /* Pack items to the end */
justify-content: space-between; /* Equal space between items */
justify-content: space-around;  /* Equal space around items */
justify-content: space-evenly;  /* Equal space between and around */

Most common: space-between for navbars, center for hero sections.

align-items — Cross Axis Alignment

Controls alignment perpendicular to the main axis:

css
align-items: stretch;    /* Fill the container height (default) */
align-items: flex-start; /* Align to top */
align-items: center;     /* Center vertically */
align-items: flex-end;   /* Align to bottom */
align-items: baseline;   /* Align text baselines */

Pro tip: display: flex; align-items: center; justify-content: center; is the classic centering trick.

flex-wrap — Wrapping

By default, flex items squeeze onto one line. Enable wrapping:

css
.container {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

Combined with gap, this creates responsive grids without media queries.

The flex Shorthand

The flex property on children controls how they grow and shrink:

css
.item { flex: 1; }          /* Grow equally to fill space */
.item-fixed { flex: 0 0 200px; } /* Never grow/shrink, fixed 200px */
.item-auto { flex: 0 1 auto; }   /* Shrink if needed, natural size */

flex: 1 is shorthand for flex-grow: 1; flex-shrink: 1; flex-basis: 0%;.

gap — Spacing Between Items

The modern way to space flex items (no more margin hacks):

css
.container {
  display: flex;
  gap: 16px;        /* Equal row and column gap */
  gap: 16px 24px;   /* Row gap, then column gap */
}

Supported in all modern browsers. It's the cleanest solution for consistent spacing.

Common Patterns

Navbar with logo left, links right:

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

Centered card content:

css
.card { display: flex; flex-direction: column; align-items: center; gap: 12px; }

Equal-width columns:

css
.columns { display: flex; gap: 16px; }
.columns > * { flex: 1; }

Flexbox pairs perfectly with visual CSS properties. Try our Box Shadow Generator to add depth to your flex layouts, or the Glassmorphism Generator for frosted-glass card effects.

Try These Tools