Layout and responsive design
Flexbox
Goal: Arrange items in a row or column and control spacing and alignment · 12 min
Flexbox lays out items in one dimension (a row or a column). Put display: flex on the container; its direct children become flex items.
Container properties:
flex-direction:row(default),column(and-reversevariants).justify-content: distribution along the main axis (the direction of flex-direction):flex-start,center,flex-end,space-between,space-around,space-evenly.align-items: alignment on the cross axis:stretch(default),flex-start,center,flex-end.gap: space between items (no margin tricks needed).flex-wrap: wrap: let items move to a new line when there is no room.
Item properties: flex: 1 lets an item grow to take the free space (items with flex: 1 share equally; flex: 2 gets double). flex-shrink, flex-basis and align-self fine-tune.
Example: three 100px items in a 400px row with justify-content: space-between sit at x = 0, 150 and 300, because the free space (100px) is divided between two gaps of 50px.
Classic uses: a navigation bar (display: flex; gap: 1rem;), centring in both directions (justify-content: center; align-items: center;), equal-height columns.
When flex-direction: column, the axes swap: justify-content is now vertical, align-items horizontal.
Worked example: Centering in both directions
- Container: display: flex; so the child becomes a flex item.
- justify-content: center centres along the main axis (horizontal for a row).
- align-items: center centres along the cross axis; the container needs a height, for example min-height: 100vh.
.hero {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}