Overview

Flexbox lays out a single row or column whose children grow, shrink, and align along one axis: nav bars, toolbars, button rows, input groups. When rows and columns must align with each other, use css-grid. The umbrella page is css.

Use flex for one dimension and grid for two

A row of buttons or a media object is flex; a page shell with sidebar, header, and footer is grid. The test is whether items on different rows must line up by column. If you use flex-wrap plus manual widths to fake a grid, write grid-template-columns: repeat(auto-fill, minmax(...)) instead.

Name the axes

flex-direction sets the main axis; the cross axis is perpendicular.

  • justify-content aligns on the main axis.
  • align-items aligns each item on the cross axis.
  • align-content aligns wrapped lines on the cross axis and does nothing without flex-wrap: wrap.

If align-items: center seems to stop working after you change direction, the axes swapped.

Use gap instead of margins

gap on flex containers has been Baseline widely available since October 2023. It never leaks past the last child, needs no :last-child overrides, and survives wrapping.

.toolbar { display: flex; gap: 0.5rem; align-items: center; }

Read flex as grow, shrink, basis

.sidebar { flex: 0 0 240px; }  /* fixed width */
.main    { flex: 1 1 0; min-width: 0; }  /* fill the rest */
.button  { flex: none; }       /* size to content */
  • flex: 1 is 1 1 0%: fill remaining space and ignore intrinsic size.
  • flex: auto is 1 1 auto: fill, but start from intrinsic size.
  • flex: none is 0 0 auto: locked to content.

Set min-width: 0 on children that must shrink

A flex item defaults to min-width: auto, so it will not shrink below its content. A long word, a wide table, or a pre inside a flex: 1 child then overflows the container. Set min-width: 0 (and min-height: 0 for column overflow), then give the content its own overflow.

.main pre { overflow-x: auto; }

Avoid common pitfalls

  • Centering with place-items. On a flex container only the align-items half applies. Use justify-content plus align-items, or switch to grid.
  • Percentage heights in a column. They need a parent with a definite height; define height or min-height on the container.
  • Wrapping on a fixed container. Items wrap by basis plus content, not by container width; set flex-basis explicitly.
  • order and tab order. order and row-reverse change only the visual order; keyboard focus follows the DOM. See accessibility.