Skip to content

Lesson 16 of 52Layout

Flexbox

Lay out items in a row or column, space and align them, let them wrap and grow, and build nav bars, card rows and sticky footers.

20 min read0/4 questions

You can now style a single box: its selectors, size, colours and type. The next problem is arranging many boxes on a page. For years, centring something vertically on a web page was a running joke among developers. Flexbox ended the joke. It is a layout mode for arranging items along one line, a row or a column, and deciding how they share space, how they line up and what happens when they run out of room. Navigation bars, button groups, card rows, media objects and page footers are all one or two flexbox declarations away. This lesson is hands-on: every section has a small live editor, so change the values and watch what happens.

Container and items

Flexbox always involves two levels. You set display: flex on a parent, which becomes the flex container. Its direct children automatically become flex items. Grandchildren are not affected; they lay out normally inside their own item.

The moment you add display: flex, three things happen. The items line up in a row instead of stacking. They shrink to fit their content instead of stretching to full width. And they all stretch to the same height as the tallest one.

HTML & CSS
<style> body { font-family: system-ui; } .row { display: flex; gap: 12px; border: 2px dashed #9ca3af; padding: 12px; } .item { background: #dbeafe; border: 2px solid #2563eb; padding: 12px; }</style><div class="row"> <div class="item">Home</div> <div class="item">Recipes with a long name</div> <div class="item">About</div></div>

Preview

Try this: delete display: flex; and watch the items stack as ordinary blocks. Put it back, then change gap: 12px to gap: 40px. The gap property adds space between items only, never on the outside edges, which is why it is cleaner than margins.

The main axis and the cross axis

Everything in flexbox is described in terms of two directions. The main axis runs the way the items flow. The cross axis runs at a right angle to it. With the default flex-direction: row, the main axis is horizontal (left to right in English) and the cross axis is vertical. Switch to column, and the two axes swap.

That swap is the key to remembering the two most-used properties:

  • justify-content positions items along the main axis.
  • align-items positions items along the cross axis.
flex-directionMain axisjustify-content moves itemsalign-items moves items
row (default)horizontalleft and rightup and down
columnverticalup and downleft and right
row-reversehorizontal, starting from the rightright and leftup and down
column-reversevertical, starting from the bottomdown and upleft and right
HTML & CSS
<style> body { font-family: system-ui; } .box { display: flex; flex-direction: row; gap: 8px; border: 2px dashed #9ca3af; padding: 8px; height: 220px; } .box div { background: #fde68a; border: 2px solid #b45309; padding: 10px 14px; }</style><div class="box"> <div>1. Chop</div> <div>2. Fry</div> <div>3. Serve</div></div>

Preview

Try this: change row to column and watch the steps stack and stretch to the full width. Then try row-reverse and column-reverse. The reversed values only change what you see: screen readers and the Tab key still follow the HTML order, so do not use them to fix the meaning of your content.

justify-content: spacing along the main axis

When the items do not fill the container, justify-content decides where the spare space goes.

ValueSpare space goes
flex-start (default)All at the end, items packed at the start
flex-endAll at the start, items packed at the end
centerEqually on both outer sides
space-betweenBetween items, none on the outer edges
space-aroundAround each item, so edges get half a gap
space-evenlyExactly equal gaps everywhere, edges included
HTML & CSS
<style> body { font-family: system-ui; } .bar { display: flex; justify-content: flex-start; border: 2px dashed #9ca3af; padding: 8px; } .bar div { background: #dcfce7; border: 2px solid #16a34a; padding: 10px; width: 60px; text-align: center; }</style><div class="bar"> <div>A</div> <div>B</div> <div>C</div></div>

Preview

Try this: go through center, flex-end, space-between, space-around and space-evenly one at a time. space-between is the one you will use most, for a logo on the left and a menu on the right.

Quick check
A container has display: flex; flex-direction: column;. Which property moves its items to the vertical middle of the container?
Need a nudge? A hint rules out a wrong answer.

align-items: lining up on the cross axis

align-items sets how items sit across the line. The default, stretch, makes them all as tall as the container (in a row), which is why flex cards in a row get equal heights for free.

ValueEffect in a row
stretch (default)Items fill the full height
flex-startItems sit at the top, at their natural height
flex-endItems sit at the bottom
centerItems are vertically centred
baselineThe first lines of text line up

To move just one item, put align-self on that item. It takes the same values.

HTML & CSS
<style> body { font-family: system-ui; } .row { display: flex; align-items: stretch; gap: 8px; height: 160px; border: 2px dashed #9ca3af; padding: 8px; } .row div { background: #ede9fe; border: 2px solid #7c3aed; padding: 8px; } .big { font-size: 2rem; }</style><div class="row"> <div>Small</div> <div class="big">Big</div> <div>Two<br>lines</div></div>

Preview

Try this: change stretch to center, then flex-start, then baseline and look at how the words "Small", "Big" and "Two" line up. Then add align-self: flex-end; to the .big rule only.

And here is the end of the old joke. Perfect centring in both directions takes three lines:

.center-me {
  display: flex;
  justify-content: center;
  align-items: center;
}

flex-wrap: when items run out of room

By default, flex items stay on one line (flex-wrap: nowrap) and shrink to fit, even if that squashes them. With flex-wrap: wrap, items that do not fit move onto a new line instead.

HTML & CSS
<style> body { font-family: system-ui; } .tags { display: flex; flex-wrap: nowrap; gap: 8px; width: 280px; border: 2px dashed #9ca3af; padding: 8px; } .tags span { background: #fee2e2; border: 2px solid #dc2626; padding: 6px 10px; white-space: nowrap; }</style><div class="tags"> <span>vegetarian</span> <span>quick</span> <span>one pot</span> <span>spicy</span> <span>family favourite</span></div>

Preview

Try this: with nowrap the tags burst out of the dashed box. Change it to wrap and they flow onto a second line, with gap spacing the rows as well. Try width: 180px too. When items wrap, align-content controls how the lines themselves are spaced inside a taller container.

Predict the outputHTML & CSS

The container is 300px wide and holds four items that are each 100px wide and cannot shrink. With flex-wrap: wrap and no gap, how many items are on the first line?

.list { display: flex; flex-wrap: wrap; width: 300px; }
.list > * { width: 100px; flex-shrink: 0; }
Need a nudge? Hints walk you through it.

flex-grow, flex-shrink and flex-basis

So far items have kept their natural size. Three properties on the items decide how they share the space:

  • flex-basis is the starting size before any growing or shrinking. The default, auto, uses the item's width or its content size.
  • flex-grow says how much of the spare space an item takes. 0 (the default) means none. If one item has 1 and another has 2, the second gets twice as much of the leftover space.
  • flex-shrink says how much an item gives up when there is not enough space. The default is 1; 0 means "never shrink below my basis".

You usually set all three at once with the flex shorthand. The default is flex: 0 1 auto. The most common value is flex: 1, which means flex: 1 1 0%: start from zero and share all the space equally.

How flexbox sizes items in a row
  1. 1. Start at flex-basiseach item's starting width
  2. 2. Compare with the containeris there space left, or too little?
  3. 3a. Spare space: growshare it by flex-grow
  4. 3b. Too little: shrinktake it away by flex-shrink

Every item starts at its flex-basis. With auto, that is its width or its content size.

1/4
HTML & CSS
<style> body { font-family: system-ui; } .row { display: flex; gap: 8px; border: 2px dashed #9ca3af; padding: 8px; } .row div { background: #e0f2fe; border: 2px solid #0284c7; padding: 10px; } .a { flex: 0 1 auto; } .b { flex: 1; } .c { flex: 0 1 auto; }</style><div class="row"> <div class="a">Logo</div> <div class="b">Search recipes</div> <div class="c">Sign in</div></div>

Preview

Try this: the search box takes all the spare space because only it can grow. Give .a flex: 1 too and they split it equally. Then set .b { flex: 2; } so the search box gets twice the share. Finally set all three to flex: 1 and notice they become equal widths, because flex: 1 starts every item from zero.

Match the pairs0/5 matched

Match each declaration to what it does.

Choose an item, then its match on the other side.

One gotcha worth knowing: by default a flex item will not shrink below the width of its longest word or widest child. A long URL or a wide code block can then push the whole row wider than the screen. Adding min-width: 0 to the item lets it shrink, and then you can handle the overflow inside it.

Common recipes

Nav bar. Logo on the left, links on the right, all vertically centred. A margin-left: auto on an item soaks up all the free space on that side, which pushes it (and everything after it) to the far end.

HTML & CSS
<style> body { font-family: system-ui; margin: 0; } nav { display: flex; align-items: center; gap: 16px; padding: 12px 16px; background: #111827; } nav a { color: white; text-decoration: none; } .logo { font-weight: 800; font-size: 1.25rem; } .push { margin-left: auto; }</style><nav> <a class="logo" href="#">Crumb</a> <a class="push" href="#">Recipes</a> <a href="#">Shop</a> <a href="#">Sign in</a></nav>

Preview

Try this: move the push class from "Recipes" to "Sign in" so only that link sits on the far right. Then remove align-items: center and notice the logo and links no longer line up neatly.

Card row. display: flex; flex-wrap: wrap; gap: 1rem; on the container and flex: 1 1 240px; on each card. Each card starts at 240px, grows to fill the row, and wraps when the row gets too narrow. For strict columns that line up in both directions, CSS Grid (next lesson) is the better tool.

Sticky footer. On a short page, you want the footer at the bottom of the window, not halfway up. Make the body a column that is at least the full screen height, and let the main content grow:

body { display: flex; flex-direction: column; min-height: 100dvh; margin: 0; }
main { flex: 1; }
Put it in order4 steps

Put the steps flexbox follows to size items in a row in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
flex container
An element with display: flex; its direct children become flex items.
main axis
The direction flex items flow in, set by flex-direction; justify-content works along it.
cross axis
The direction at a right angle to the main axis; align-items works along it.
gap
Space between flex or grid items, never on the outer edges.
flex-wrap
Whether items stay on one line (nowrap) or move to new lines when they run out of room (wrap).
flex-grow
How much of the spare space an item takes, relative to its siblings.
flex-basis
An item's starting size before growing or shrinking.