Flexbox

CSS · Essentials · 14 min

Flexbox handles navbars, toolbars, centering and card rows: most one-dimensional layout on the web.

display: flex turns an element into a flex container and its direct children into flex items, laid out along one axis.

  • flex-direction: row (default) or column sets the main axis. The other is the cross axis.
  • justify-content distributes items along the main axis: flex-start, center, space-between, space-around, space-evenly.
  • align-items aligns them on the cross axis: stretch (default, equal heights), center, flex-start, baseline.
  • gap: 1rem puts space between items without margin tricks.
  • flex-wrap: wrap lets items wrap onto new lines instead of shrinking.

Each item's size is controlled with the flex shorthand, flex: grow shrink basis:

  • flex: 1 means grow to share free space equally (basis 0).
  • flex: none keeps the content size, neither growing nor shrinking.
  • flex: 0 0 200px makes a fixed 200px column.

Two classic patterns: perfect centering with display: flex; justify-content: center; align-items: center, and pushing one item to the far end with margin-left: auto, since auto margins absorb free space.

Remember that justify-content works on the main axis, so it becomes vertical when flex-direction: column. And flexbox is one-dimensional: when you need rows and columns to line up, use grid.

Example

/* <header class="bar"><a>Logo</a><nav>...</nav><button>Sign in</button></header> */
.bar {
  display: flex;
  align-items: center;           /* vertical centering in a row */
  gap: 1rem;
  padding: 0.5rem 1rem;
}
.bar button { margin-left: auto; }   /* pushes the button to the far right */

.center {                        /* center anything both ways */
  display: flex; justify-content: center; align-items: center;
  min-height: 50vh;
}

.cards { display: flex; flex-wrap: wrap; gap: 1rem; }
.cards > * { flex: 1 1 250px; }  /* at least ~250px, grow to fill each row */

.sidebar-layout { display: flex; }
.sidebar-layout aside { flex: 0 0 240px; }   /* fixed */
.sidebar-layout main  { flex: 1; }           /* takes the rest */

Remember

  • justify-content = main axis, align-items = cross axis
  • gap spaces items; flex-wrap allows new lines
  • flex: 1 shares free space; flex: none keeps content size
  • margin-left: auto pushes an item to the end

Watch out for

  • Expecting justify-content to center vertically in a flex-direction: column container; there it's align-items for horizontal.

Check yourself

  1. In a flex-direction: column container, which property centers items horizontally?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: developer.mozilla.org/en-US/docs/Web/CSS/Guides/Flexible_box_layout/Basic_concepts