Code Reference

Flexbox

CSS · Reference cheat sheet

Flexbox

CSS · Reference cheat sheet


📋 Overview

Flexbox is a one-dimensional layout model for distributing space and aligning items along a row or column. Set display: flex or inline-flex on a container, then control direction, wrapping, alignment, and growth with flex properties. Use Flexbox for toolbars, navs, form rows, and equal-height media objects; use Grid when you need two-dimensional tracks or overlapping areas.

Main axis follows flex-direction; cross axis is perpendicular. Logical alignment (start / end) respects writing mode better than physical left / right.

🔧 Core concepts

Container properties

PropertyCommon valuesRole
flex-directionrow | row-reverse | column | column-reverseMain axis
flex-wrapnowrap | wrap | wrap-reverseMulti-line flex
flex-flowshorthand of direction + wrap
justify-contentstart end center space-between space-around space-evenlyMain-axis distribution
align-itemsstretch start end center baselineCross-axis, one line
align-contentsame family as justifyCross-axis when wrapped
gap<row-gap> <column-gap>Spacing between items

Item properties

PropertyRole
flex-growExtra free space factor (default 0)
flex-shrinkShrink factor (default 1)
flex-basisInitial main size (auto, length, %, content)
flexShorthand: grow shrink basis — prefer flex: 1 / flex: none
align-selfOverride align-items for one item
orderVisual order (avoid for tab order / accessibility)

Useful shorthand recipes

DeclarationMeaning
flex: 11 1 0% — share space equally from zero basis
flex: auto1 1 auto — grow/shrink from content size
flex: none0 0 auto — sized by content, don’t flex
flex: 0 0 12remFixed main size

💡 Examples

Toolbar

.toolbar {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding-inline: 1rem;
}

.toolbar__spacer {
  flex: 1;
}

Media object

.media {
  display: flex;
  gap: 1rem;
  align-items: flex-start;
}

.media__body {
  flex: 1;
  min-inline-size: 0; /* allow text truncation */
}

Wrapping chip list

.chips {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

Equal-height columns (row)

.pricing {
  display: flex;
  gap: 1rem;
  align-items: stretch; /* default */
}

.pricing > .plan {
  flex: 1 1 0;
}

⚠️ Pitfalls

  • Forgetting min-inline-size: 0 (or min-width: 0) on flex children so long text overflows instead of shrinking.
  • Using order to reshuffle content without updating DOM order—keyboard and screen-reader order stay source-based.
  • Mixing justify-content: space-between with gap expectations; gap is fixed space between items, not a substitute for margins in every case.
  • Default flex-shrink: 1 unexpectedly crushing icons—set flex: none or flex-shrink: 0 on fixed chrome.
  • Choosing Flexbox for a full page 2D layout that Grid expresses more clearly with template areas.

On this page