Flexbox &
Grid

Two ways to arrange boxes on a page. Every panel below is live — change a value and watch the boxes move.

Start by clicking things. The explanations are below.

Part one: Flexbox

Flexbox arranges things along a single line — a row or a column. Reach for it when you have a handful of items that should sit next to each other and share the space sensibly.

01 Making a flex container

One declaration starts everything: display: flex on the parent. The parent becomes a flex container and its direct children become flex items.

Notice what happens the moment you switch it on. The boxes stop stacking vertically and line up side by side, and they stretch to the same height even though their content differs.

Flexbox only affects direct children. A grandchild is not a flex item.

02 The two axes

Every flex container has a main axis, drawn here in blue, and a cross axis, drawn in pink. Items flow along the main axis.

flex-direction decides which is which. With row the main axis runs left to right; with column it runs top to bottom and the two arrows swap places.

This is the single most useful thing to hold in your head. Every other flex property is described in terms of these two axes, so "which way is main right now?" answers most questions.

The -reverse values flip the direction items flow, not the direction of the page. Item 1 ends up last.

03 Spacing along the main axis

justify-content distributes leftover space along the main axis. It only has something to do when the items don't already fill the line.

The three space-* values differ in where they put the gaps at the ends: space-between puts none, space-around gives each item a half-size gap on both sides, and space-evenly makes every gap identical.

Switch flex-direction to column and try again. The same values now push items up and down, because justify-content follows the main axis wherever it points.

04 Aligning across the cross axis

align-items is the same idea turned ninety degrees: it positions items along the cross axis.

The default is stretch, which is why boxes of different content ended up the same height in lesson one. Choose flex-start, center or flex-end and each item shrinks back to its natural size.

baseline is the specialist: it lines up the first line of text in each item, which is what you want for labels of different sizes sitting next to each other.

To move one item differently from its siblings, set align-self on that item.

05 Space between items

gap sets a fixed distance between items without touching the outside edges. It works in both flexbox and grid, and it replaces the old habit of putting a margin on every item and then removing it from the last one.

You can set the two directions separately with row-gap and column-gap, or give gap two values: row first, then column.

gap and justify-content stack. The gap is a minimum; space-between still spreads whatever is left over.

06 Letting items wrap

By default a flex container refuses to break the line — it squashes items instead. flex-wrap: wrap lets items that don't fit move onto a new line.

Once there are several lines, a third alignment property wakes up: align-content, which spaces the lines along the cross axis. Compare it with align-items, which positions items within their own line.

Narrow your browser window while nowrap is selected to see the squashing. That's flex-shrink doing its job, which is lesson seven.

07 Growing and shrinking

Everything so far has been set on the container. flex is set on the items, and it decides how they divide up the space.

It is shorthand for three values: flex-grow flex-shrink flex-basis. Read 1 1 0 as "take a share of the free space, be willing to shrink, start from nothing". An item with grow 2 takes twice the share of an item with grow 1.

0 0 200px is the opposite instruction: stay exactly 200 pixels, whatever happens. That's how you pin a sidebar next to flexible content.

The common pair is flex: 1 (shorthand for 1 1 0) on things that should share, and flex: none on things that shouldn't.

Part two: Grid

Grid works in two directions at once. You define columns and rows first, then place things into the cells they create. Reach for it when the layout has a structure you could sketch on paper before you knew what was going in it.

08 Drawing the columns

display: grid plus grid-template-columns defines the shape of the layout. Items then fill the cells in order, wrapping to a new row automatically.

The fr unit means "one share of the free space". 1fr 1fr 1fr is three equal columns; 1fr 2fr 1fr makes the middle one twice as wide. You can mix in fixed sizes: 200px 1fr gives a fixed sidebar and a flexible rest.

The numbers above the grid are the column lines. There is always one more line than there are columns, and you'll use those numbers in lesson eleven.

09 repeat, minmax and auto-fit

Writing 1fr 1fr 1fr 1fr 1fr 1fr gets old. repeat(6, 1fr) says the same thing.

minmax() gives a track a floor and a ceiling: minmax(140px, 1fr) means "never narrower than 140px, otherwise share the space".

Put them together with auto-fit and the grid decides how many columns fit by itself. Drag your browser window narrower with the last option selected — the columns rearrange with no media query anywhere.

auto-fill is the sibling of auto-fit. It keeps the empty tracks instead of collapsing them, so leftover items don't stretch to fill the row.

10 Rows and gaps

Rows work the same way with grid-template-rows, and gap behaves exactly as it did in flexbox.

You often don't need to declare rows at all. Any row the browser creates for you is an implicit row, sized to its content. Set grid-auto-rows if you want those automatic rows to share a size.

A row of 1fr only means something if the container has a height to divide up. Without one, 1fr and auto look identical.

11 Making an item cover more cells

Items can claim more than one cell. grid-column: span 2 makes an item two columns wide starting wherever it landed.

Or place it by line number: grid-column: 1 / 3 means "start at line 1, end at line 3" — those are the numbers you saw along the top in lesson eight. grid-column: 1 / -1 is a useful trick meaning "all the way across", counting backwards from the last line.

grid-row does the same thing downwards, which is how a hero image ends up two rows tall.

Click any block in the panel to change how many columns it spans.

12 Naming the areas

grid-template-areas lets you draw the layout as text. Each quoted string is a row, each word is a cell, and repeating a name makes that area stretch across the cells it covers.

Then each item just says where it belongs: grid-area: sidebar. Nothing has to know about line numbers.

Best of all, rearranging the page for a narrow screen means rewriting the picture inside a media query. The elements themselves don't change at all.

Use a full stop as a name to leave a cell deliberately empty.

13 Aligning inside the tracks

Grid has two families of alignment, and mixing them up is the usual source of confusion.

justify-items and align-items move each item inside its own cell. They default to stretch, which is why items normally fill their cell edge to edge.

justify-content and align-content move the whole grid inside the container. Those only do something when the tracks are smaller than the space available — so try them with fixed-width columns.

Remember: justify-* works across columns, align-* works down rows. The *-items pair moves items, the *-content pair moves tracks.

Part three: putting it to work

You will use both, usually on the same page and often nested inside one another.

14 Which one do I use?

The honest answer is that either will usually work. But there's a question that sorts most cases quickly: do I care about both directions at once?

If you're lining up a nav bar, a row of buttons, or an icon next to a label, that's one direction and flexbox is less code. If you're laying out a page, a card gallery, or a form with labels lined up against fields, that's two directions and grid will save you from a pile of wrapper divs.

The other useful split is who decides the sizes. Grid is the parent laying out a plan in advance. Flexbox lets the content push back.

The situationFlexboxGrid
DirectionOne line at a timeRows and columns together
Who sizes thingsContent nudges the layoutLayout is decided up front
Nav bar, toolbar, button rowYesOverkill
Page skeleton with header, sidebar, footerFights youYes
Card gallery that reflowsNeeds wrap plus basis mathsauto-fit and done
Centring one thing in a boxFineAlso fine
Overlapping elementsNot reallyYes, same cell

Nesting is normal and expected: a grid page whose header is a flex row is probably the most common layout on the web.

15 Your turn

The pink outline shows the arrangement to aim for: the three boxes pushed apart across the full width, and sitting on the bottom edge.

Set the two properties in the panel to match it, then check your answer. There is exactly one correct pair here.

When it clicks, try to say out loud why each one does what it does — which axis is it working on?