EMZETT.
Login

CSS flexbox: one-dimensional layouts

In short: Flexbox arranges elements in a row or column, distributes free space and aligns them. It is the standard tool for menus, card rows and centred content.

In more detail: You turn a container into a “flex box” with display: flex. Its direct children become flex items and follow the container’s rules.

In Depth

  • Main axis: flex-direction: row (default) or column. The cross axis is perpendicular to it.
  • Aligning: justify-content distributes along the main axis (flex-start, center, space-between, space-around). align-items aligns across (stretch, center, flex-start).
  • Spacing: gap: 1rem sets gaps without margin tricks.
  • Wrapping: flex-wrap: wrap lets items wrap onto the next line.
  • Growing and shrinking: flex: 1 lets an item fill free space, flex: 0 0 200px gives a fixed width. Written out: flex-grow, flex-shrink, flex-basis.
  • Centring: display:flex; justify-content:center; align-items:center; centres a child horizontally and vertically.
  • When Grid? For two-dimensional grids (rows and columns at once) CSS Grid is better. Flexbox is meant for one direction.

See also: CSS, media queries