Skip to content

Chapter 2 of 7

Flexbox Deep Dive

A flex container has two axes. The main axis is the direction children flow, controlled by \(flex-direction\) (with options \(row\), \(row-reverse\), \(column\), \(column-reverse\)), and \(row\) is the default. The cross axis is perpendicular to that. Alignment along the main axis is governed by \(justify-content\), which defaults to \(flex-start\) and offers \(center\), \(flex-end\), \(space-between\), \(space-around\), and \(space-evenly\). Alignment along the cross axis is governed by \(align-items\), which defaults to \(stretch\) so that children fill the cross axis — the reason flex columns in a row are naturally the same height.

Every flex item is sized by three properties: \(flex-grow\), \(flex-shrink\), and \(flex-basis\). The basis is the starting size before free space is distributed; grow distributes extra space, shrink takes it away under overflow. The shorthand \(flex\) is the everyday form: \(flex: 1\) is \(1 1 0%\) (equal fills regardless of content), \(flex: auto\) is \(1 1 auto\) (grow and shrink from content size), \(flex: initial\) is \(0 1 auto\) (shrink but do not grow), and \(flex: none\) is \(0 0 auto\) (no grow, no shrink). Setting \(flex-basis: 0\) makes widths purely proportional because the starting size is ignored; \(flex-basis: auto\) starts from the content's intrinsic size.

Wrapping onto multiple lines requires \(flex-wrap: wrap\) (or \(wrap-reverse\)); the shorthand \(flex-flow: row wrap\) combines direction and wrap. When items wrap, \(align-content\) distributes the resulting lines along the cross axis, while \(align-items\) continues to align each item within its own line. \(gap\) works on flex containers in modern browsers and replaces the older "margins on every child except the last" pattern. One often-overlooked trap: flex items default to \(min-width: auto\), which means they cannot shrink below their content's minimum size and can blow out the layout. The standard fix is \(min-width: 0\) on the item. For the visual equivalent of CSS Grid's \(1fr\) in flex, simply set \(flex: 1\) on each child.

All chapters
  1. 1The Fundamental Decision
  2. 2Flexbox Deep Dive
  3. 3CSS Grid Deep Dive
  4. 4Alignment and Centering
  5. 5Common Layout Patterns
  6. 6Responsive Design and Modern Queries
  7. 7Pitfalls, Accessibility, and the Future

Drill it

Reading is not remembering. These come from the CSS Grid Vs Flexbox When To Use Which deck:

Q

One-line summary: when Grid vs Flexbox?

Grid: 2D layout (rows AND columns), known structure.Flexbox: 1D layout (row OR column), content-driven.

Q

Center a single element on the page — Grid or Flex?

Either works. display: grid; place-items: center; or display: flex; align-items: center; justify-content: center;

Q

Make a sidebar + main layout with Grid?

grid-template-columns: 250px 1fr;

Q

Same layout with Flex?

display:flex; with sidebar flex: 0 0 250px and main flex: 1.