CSS Flexbox & Grid
Stop guessing at layout. The properties that actually center, distribute, and arrange things — flexbox for one dimension, grid for two.
Flexbox (one axis)
- Turn on
display: flex· direction:flex-direction: row | column- Along main axis
justify-content: center | space-between | space-around | flex-start- Across cross axis
align-items: center | stretch | flex-start | baseline- Wrap
flex-wrap: wrap· shorthandflex-flow: row wrap- Item grow/shrink
flex: 1(grow) ·flex: 0 0 200px(fixed basis)- Gap
gap: 1rem— spacing without margins
Grid (two axes)
- Turn on
display: grid- Columns
grid-template-columns: 1fr 2fr· repeat:repeat(3, 1fr)- Responsive columns
repeat(auto-fit, minmax(200px, 1fr))— the famous one- Gaps
gap: 1rem·row-gap/column-gap- Span cells
grid-column: span 2·grid-row: 1 / 3- Named areas
grid-template-areas: "hd hd" "sb mn"thengrid-area: hd
Centering (the eternal question)
- Center anything (flex)
display:flex; justify-content:center; align-items:center- Center anything (grid)
display:grid; place-items:center- Center a block
margin-inline: autowith a set width
Which one?
- Flex
- Content in a single row or column — navbars, toolbars, button rows.
- Grid
- Two-dimensional layouts — page skeletons, card galleries, forms.
- Both
- Grid for the page, flex inside each cell. They compose.