Skip to content

Chapter 4 of 7

Alignment and Centering

Alignment in Flex and Grid shares the same vocabulary but applies slightly differently. \(justify-content\) distributes items along the main axis (Flex) or aligns the whole grid within its container (Grid); \(align-items\) aligns each item along the cross axis (Flex) or within its cell (Grid). \(align-content\) goes one level up in both: when multiple lines exist (wrapped flex or implicit grid rows), it distributes those lines along the cross axis. \(align-self\) and \(justify-self\) override the parent's alignment for a single item — important to know that \(justify-self\) has no effect in Flexbox, where cross-axis alignment is done with \(align-self\) or \(margin: auto\).

The shorthand \(place-*\) properties combine align and justify versions. \(place-items: center\) on a grid (or \(place-content: center\) on a flex container) centers any child with one declaration. \(place-self: end\) pins one item to the bottom-right of its cell. Margins still work in flex: \(margin-left: auto\) on the last flex child pushes it to the end, which is the classic "logo on the left, links on the right" navbar trick. For Grid, the analogue of flex's \(space-between\) is usually handled at the track level rather than via \(justify-content\).

A concrete comparison helps cement the model. \(display: grid; place-items: center;\) and \(display: flex; align-items: center; justify-content: center;\) both center a single child. With multiple children, Flexbox's \(justify-content\) spreads them along the row (\(space-between\) leaves no edge gap, \(space-around\) gives half-gap at the edges making interior gaps look larger, \(space-evenly\) gives identical spacing everywhere). In Grid, the equivalent "spread" effect is generally achieved by track sizing rather than content alignment — for instance \(grid-template-columns: repeat(3, 1fr)\) places three equal gaps of free space between four items.

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.