Loading

T2 CSS · Lesson 5

Flexbox

Flex containers and items, the main and cross axes; sharing space with justify-content and gap; lining up with align-items; wrapping onto new lines; and sizing items with grow, shrink, basis, flex: 1 and an auto margin.

  • turn a box into a flex container, and name its main and cross axes
  • share the space along a row with justify-content and gap
  • line items up across the row with align-items and align-self
  • let a row wrap onto new lines on narrow screens, and say when items shrink
  • size items with flex-grow, flex-shrink, flex-basis and the flex shorthand, and push one aside with an auto margin
About 60 minutesChecked against Node.js on the laptop (the kit runs every code block with it) 22.23.1 (2026-11-06)Play this lesson's games

The back cover

A shelf of books, a row of buttons, a line of cards: much of a page is things in a row, sharing the space. Flexbox lets one container decide how its children share that line, like people spreading out along the wall of a lift.

These pages show a flex container and its items, and the two axes they follow. They show how leftover space is shared along the row, how items line up across it, and what happens when the row is too long. Then they show how each item takes its own share, with grow, shrink and basis.

Before you start

The story: Five notices in a row

The market warden wants the five stall notices of the Fair side by side on the square's long board, with equal gaps, each one's price at the same height. Corin has nudged each notice into place by hand, a margin here, a margin there.

It looks fine on the long board. Then a courier opens the same board on a palm-sized panel, and three of the five notices hang off its right edge, out of sight.

Meher shakes her head and leads you to a loom at the back of the Tailors' Hall, its threads strung in one long row. "Stop placing pieces one by one," she says. "Give the row its rule, and let the row place them."

Lesson 3 built single boxes and stacked them one above another. Real pages also need boxes side by side: a row of product cards, a menu across the top, a logo on the left and a cart on the right. Flexbox is the CSS tool for laying boxes out in a row or a column and sharing the space between them. It builds on these ideas; each has a tiny example.

What you already knowA tiny exampleWhere it comes back
display decides the kind of box.block, inline, inline-block.display: flex is one more kind.
Block boxes stack downwards.Two divs sit one above the other.In a flex row, they sit side by side instead.
The box model.Content, padding, border, margin; box-sizing.Flex items are boxes, with all four layers.
margin: 0 auto centres a box.Auto margins share the leftover space.In flexbox, an auto margin pushes an item to the far end.
% and fixed widths.width: 50% of a 600px parent is 300px.Flexbox can share space without any widths at all.
Source order and the Tab key.Keyboard users move in the HTML's order.Flexbox can change the visual order; that has a cost.
Lists for menus.A nav holding a ul of links.A flex row turns the list into a menu bar.
Measuring what was drawn.getBoundingClientRect().Every block checks where each box landed, in pixels.
A loom's row of threads.Threads strung side by side, evenly spaced.A flex container holds its items the same way.

By the end of this lesson you will be able to:

  • turn a box into a flex container, and name its main and cross axes;
  • share the space along a row with justify-content and gap;
  • line items up across the row with align-items and align-self;
  • let a row wrap onto new lines on narrow screens, and say when items shrink;
  • size items with flex-grow, flex-shrink, flex-basis and the flex shorthand, and push one aside with an auto margin.

In one line

Flexbox lays boxes out in a row or column and shares the space between them; you need lesson 3's boxes and display, and the HTML step's source order.

A flex container and its items

At a glance

Flexbox lays things out in a line and lets them share the space. You write display: flex on a container, and its direct children become flex items. They line up along the main axis, which is a row by default.

The flex-direction property can turn the main axis into a column instead. The cross axis always runs across the main axis. Every flexbox property is about one of these two axes, so knowing which way each one runs is half the work.

Take a guess: If a list has display: flex, do the grandchildren inside each list item also become flex items?

Three people walk into a lift. Nobody tells each one where to stand: they spread themselves along the wall, side by side. The lift is the container, and the people arrange themselves inside it. Flexbox works the same way: you give rules to the container, and its children arrange themselves.

Flex container and flex items

An element with display: flex is a flex container. Its direct children become flex items, laid out in a row by default, side by side.

<!DOCTYPE html>
<style>
  body { margin: 0; }
  .stall { width: 100px; height: 40px; background-color: gold; }
  .board { display: flex; width: 600px; }
</style>
<div class="board">
  <div class="stall">Rice</div>
  <div class="stall">Dal</div>
  <div class="stall">Atta</div>
</div>

Checked in Chrome

  • the three stalls sit side by side, at 0, 100 and 200 pixels from the left
  • all on one row, at the same height

Without display: flex, these three divs would stack downwards, one per line, as blocks always do. One line on the container turned them into a row. Nothing was written on the stalls themselves.

A memory aid

The rule goes on the parent. display: flex is written on the container; the children follow. Only their direct children: grandchildren are not flex items.

Two axes

A flex container has two directions, called axes. The main axis is the direction the items are laid out in: left to right in a row. The cross axis runs across it: top to bottom in a row. Every flex property works along one axis or the other, so this one idea unlocks the rest of the lesson.

Main axisCross axis
in a row (the default)left to righttop to bottom
in a columntop to bottomleft to right
sharing space along itjustify-contentalign-items

flex-direction: a row or a column

flex-direction sets the main axis: row (the default) or column. A column stacks the items downwards, like ordinary blocks, but with every flex tool still working, such as gap.

<!DOCTYPE html>
<style>
  body { margin: 0; }
  .stall { width: 100px; height: 40px; background-color: gold; }
  .list { display: flex; flex-direction: column; gap: 10px; width: 600px; }
</style>
<div class="list">
  <div class="stall">Rice</div>
  <div class="stall">Dal</div>
</div>

Checked in Chrome

  • a column: the second stall starts at 50, below the first's 40 pixels and a 10px gap
  • both on the left edge

When the direction is a column, the axes swap: the main axis now runs down the page. That matters in the next sections, where justify-content always works along the main axis, whichever way it runs.

Worked example 1

A shop's top bar holds a logo, a menu and a cart, written as three divs. They stack on three lines. Make them one row, and check each one's position.

What we have: three divs that stack, and the wish for a row

What we need: one rule on their parent

The plan: display: flex on the bar; its three children become items in a row

<!DOCTYPE html>
<style>
  body { margin: 0; }
  .stall { width: 100px; height: 40px; background-color: gold; }
  .bar { display: flex; width: 600px; }
</style>
<div class="bar">
  <div class="stall">Logo</div>
  <div class="stall">Menu</div>
  <div class="stall">Cart</div>
</div>

Checked in Chrome

  • one row: 0, 100, 200
  • all at the top

.bar { display: flex; }: the three divs become flex items in one row.

Check: the browser drew them side by side at the same height.

A path that fails: Writing display: flex on each of the three divs. Each one becomes a container for its own text, and the three still stack, because their parent is an ordinary block.

Worked example 2

A site's menu is a ul of four links inside a nav, from the HTML step. It shows as a bulleted list, one link per line. Turn it into a menu bar across the top, with 24px between the links and no bullets.

What we have: a ul of four li, each holding a link

What we need: the four links in one row, spaced, without bullets

The plan: the ul is the parent of the li elements, so it becomes the flex container; remove its bullets and its default padding

<!DOCTYPE html>
<style>
  body { margin: 0; }
  nav ul {
    display: flex;
    gap: 24px;
    list-style: none;
    padding: 0;
    margin: 0;
  }
</style>
<nav>
  <ul>
    <li><a href="/">Home</a></li>
    <li><a href="/offers">Offers</a></li>
    <li><a href="/help">Help</a></li>
    <li><a href="/cart">Cart</a></li>
  </ul>
</nav>

Checked in Chrome

  • the four links sit on one line
  • with no bullets
  • and 24px between neighbours
  • The li elements are the ul's children, so display: flex goes on the ul, not on the nav or the links.
  • list-style: none removes the bullets; padding: 0 removes the space the browser leaves for them.
  • nav ul { display: flex; gap: 24px; list-style: none; padding: 0; margin: 0; }

    Check: the check finds the four items on one line, without bullets, exactly 24px apart.

    When you are stuck: flex containers

    Write display: flex on the parent of the boxes you want in a row, not on the boxes.

    Only direct children become items; a box inside a box is not one.

    Row or column decides the axes: in a row, the main axis runs left to right.

    Your turn

    Where does display: flex go: on the container or on its items?Tap to reveal
    1. The lift, or the people?

    On the container.

    In a row, which way does the cross axis run?Tap to reveal
    1. Across the main axis.

    Top to bottom.

    What does flex-direction: column do to the main axis?Tap to reveal
    1. Which way are the items laid out?

    It turns it top to bottom, so the items stack downwards.

    Did you know?

    Flexbox changed its spelling twice

    Flexbox changed its spelling twice before it settled. A W3C draft of 23 July 2009 switched it on with display: box. A draft of 29 November 2011 used display: flexbox instead. Then the Candidate Recommendation of 18 September 2012 used display: flex, the form this lesson uses.

    Why it fits here: If you meet display: box or display: flexbox on an old page, it is an early spelling of this topic's display: flex.

    Sources: W3C: Flexible Box Layout, Working Draft 2009; W3C: Flexible Box Layout, Working Draft 2011; W3C: Flexible Box Layout, Candidate Recommendation 2012

    A row starts where the writing starts

    A flex row does not always run from left to right. The Flexbox standard says a row's main axis has the same orientation as the inline axis of the writing mode, so it runs the way lines of text run. On a page in a right-to-left script, such as Hebrew or Arabic, the first flex item sits at the right.

    Why it fits here: This topic's main axis is a row by default, and this shows that a row follows the language of the page.

    Sources: W3C: CSS Flexible Box Layout; W3C: CSS Writing Modes Level 4

    In one line

    Writing display: flex on a container makes its direct children flex items. They are laid out along the main axis (a row by default, or a column with flex-direction), and the cross axis runs across it.

    Sharing the space along the row: justify-content and gap

    At a glance

    Three stalls on a long board leave space over. The justify-content property, written on the container, decides where that leftover space goes along the main axis: all at the end, all at the start, around the middle, or shared between and around the items.

    Its values are flex-start, flex-end, center, space-between, space-around and space-evenly. The gap property is different: it sets a fixed space between neighbouring items only, never at the edges, whatever the leftover space. Use gap when the space between items should never change.

    Take a guess: If three 100px items sit in a 600px row with justify-content: space-between, where does the middle item start?

    Three stalls on a 600-pixel board take 300 pixels; 300 pixels are left over. Where should the leftover go: all at the end, split evenly between the stalls, or shared on both sides? justify-content, written on the container, decides how the leftover space is shared along the main axis.

    justify-contentThe leftover space goesThree 100px stalls in 600px start at
    flex-start (the default)all at the end0, 100, 200
    flex-endall at the start, so the items sit at the end300, 400, 500
    centerhalf before, half after150, 250, 350
    space-betweenbetween the items only; none at the edges0, 250, 500
    space-aroundaround each item: half-size gaps at the edges50, 250, 450
    space-evenlyin equal gaps everywhere, edges included75, 250, 425
    <!DOCTYPE html>
    <style>
      body { margin: 0; }
      .board { display: flex; width: 600px; justify-content: space-between; }
      .stall { width: 100px; height: 40px; background-color: gold; }
    </style>
    <div class="board">
      <div class="stall">Rice</div>
      <div class="stall">Dal</div>
      <div class="stall">Atta</div>
    </div>

    Checked in Chrome

    • space-between: the first at the left edge, the last at the right, the middle one between

    The 300 leftover pixels were split into the two gaps between the three stalls: 150 each. The first stall starts at 0 and the last ends at 600, flush with the edges.

    <!DOCTYPE html>
    <style>
      body { margin: 0; }
      .board { display: flex; width: 600px; justify-content: space-evenly; }
      .stall { width: 100px; height: 40px; background-color: gold; }
    </style>
    <div class="board">
      <div class="stall">Rice</div>
      <div class="stall">Dal</div>
      <div class="stall">Atta</div>
    </div>

    Checked in Chrome

    • space-evenly: four equal gaps of 75, edges included

    Here 300 pixels became four equal gaps, one before, two between, one after: 300 ÷ 4 = 75 pixels each.

    gap: space between the items, and only between

    gap puts a fixed space between neighbouring items, never at the outer edges. It is the clean way to space a row: no margins on the items, and no extra space at the ends.

    <!DOCTYPE html>
    <style>
      body { margin: 0; }
      .board { display: flex; width: 600px; justify-content: center; gap: 20px; }
      .stall { width: 100px; height: 40px; background-color: gold; }
    </style>
    <div class="board">
      <div class="stall">Rice</div>
      <div class="stall">Dal</div>
      <div class="stall">Atta</div>
    </div>

    Checked in Chrome

    • center with a 20px gap: 300 + 20 + 20 = 340 pixels of stalls and gaps, centred, so the row starts at 130

    Work it out: the stalls and gaps take 100 + 20 + 100 + 20 + 100 = 340 pixels. The leftover, 600 − 340 = 260, is split half before and half after, so the row starts at 130.

    A memory aid

    justify: along the main axis; gap: between neighbours. In a row, justify-content spreads the items left and right; the next section's align-items moves them up and down.

    Worked example 3

    A menu bar 600 pixels wide holds four links, each 100 pixels wide. The links should be spread so that the first touches the left edge, the last touches the right edge, and the gaps between them are equal. Choose the value and work out where each link starts.

    What we have: four 100px links in a 600px bar, flush with both edges, equal gaps

    What we need: the justify-content value, and each link's left edge

    The plan: flush with both edges and gaps only between: space-between; the leftover is 600 − 400 = 200, shared by 3 gaps

    1. Leftover: 600 − 4 × 100 = 200 pixels.
    2. Three gaps between four links: 200 ÷ 3 ≈ 66.67 pixels each.
    3. So the links start at 0, about 167, about 333, and 500.
    <!DOCTYPE html>
    <style>
      body { margin: 0; }
      .menu { display: flex; width: 600px; justify-content: space-between; }
      .menu a { width: 100px; }
    </style>
    <nav class="menu">
      <a href="/">Home</a>
      <a href="/offers">Offers</a>
      <a href="/help">Help</a>
      <a href="/cart">Cart</a>
    </nav>

    Checked in Chrome

    • the links start at 0, 167, 333 and 500 (rounded)

    justify-content: space-between: the links start at 0, about 167, about 333 and 500.

    Check: the browser placed them at exactly the edges worked out by hand, to the nearest pixel.

    A path that fails: Using margins on each link to spread them. The gaps then depend on the bar's width, and on a narrower screen the last link falls onto a new line or off the edge.

    When you are stuck: justify-content

    Ask where the leftover space should go: at the end, at the start, on both sides, between, around or evenly.

    Only space between the items, a fixed amount: gap.

    Nothing happens? The items may already fill the row, so there is no leftover to share.

    Your turn

    Which value puts the first item at the left edge, the last at the right, and equal gaps between?Tap to reveal
    1. The space goes only between.

    space-between.

    Two 100px items in a 500px row, justify-content: center. Where does the first start?Tap to reveal
    1. Leftover 300, half before.

    At 150px.

    Does gap add space at the outer edges of the row?Tap to reveal
    1. Only between neighbours.

    No: only between items.

    Did you know?

    The sixth value came from elsewhere

    The Flexbox standard lists only five values for justify-content: flex-start, flex-end, center, space-between and space-around. The sixth value in this topic, space-evenly, is defined in a separate standard, CSS Box Alignment, which covers alignment for block, table, flex and grid layout. It spreads the items evenly, with a full-size space at either end.

    Why it fits here: It is why space-evenly is missing from the Flexbox standard's own list of this topic's values.

    Sources: W3C: CSS Flexible Box Layout; W3C: CSS Box Alignment Level 3

    gap started life in grid

    The gap property began as grid-gap, with grid-row-gap and grid-column-gap, for grids only. The Grid standard's own list of changes records that those three were replaced with row-gap, column-gap and gap, now defined in CSS Box Alignment, the standard shared by block, table, flex and grid layout. Today the same gap property works in a flex row too.

    Why it fits here: This topic's gap, between neighbouring flex items, is that renamed grid property.

    Sources: W3C: CSS Grid Layout; W3C: CSS Box Alignment Level 3

    In one line

    justify-content shares the leftover space along the main axis (flex-start, flex-end, center, space-between, space-around, space-evenly); gap sets a fixed space between neighbours only.

    Lining up across the row: align-items

    At a glance

    Photos of different heights on a wall can line up by their tops, their bottoms or their middles. In a flex row, the align-items property, on the container, chooses how items line up along the cross axis, which runs up and down.

    Its default, stretch, makes items without a height of their own fill the row, so cards come out level. The other values are flex-start, center, flex-end and baseline. The align-self property changes it for one item, and justify-content: center with align-items: center centres something both ways.

    Take a guess: If three cards in a flex row hold different amounts of text, are they the same height by default?

    Hang three photos of different heights on a wall. You can line up their top edges, their bottom edges, or their middles; each looks different. In a flex row, align-items, on the container, chooses how items line up along the cross axis: up and down, in a row.

    align-itemsEach item isLike photos with
    stretch (the default)stretched to the full height of the row, if it has no height of its ownframes all cut to the same height
    flex-startat the toptheir top edges in line
    centerin the middletheir middles in line
    flex-endat the bottomtheir bottom edges in line
    baselinelined up by the bottom of their first line of texttheir captions in line

    stretch: why cards come out the same height

    <!DOCTYPE html>
    <style>
      body { margin: 0; }
      .row { display: flex; height: 120px; width: 600px; }
      .card { width: 100px; background-color: gold; }
    </style>
    <div class="row">
      <div class="card">Rice</div>
      <div class="card">Dal, with a long description</div>
    </div>

    Checked in Chrome

    • both cards stretch to the row's full 120px, whatever their text

    This is one of flexbox's gifts: a row of cards with different amounts of text comes out level, all the same height, with no height set on any card. The stretch works only on items with no height of their own.

    center: in the middle, at last

    <!DOCTYPE html>
    <style>
      body { margin: 0; }
      .row { display: flex; align-items: center; height: 120px; width: 600px; }
      .small { width: 100px; height: 40px; background-color: gold; }
      .big { width: 100px; height: 80px; background-color: teal; }
    </style>
    <div class="row">
      <div class="small">Rice</div>
      <div class="big">Dal</div>
    </div>

    Checked in Chrome

    • the 40px item starts 40 down, the 80px item 20 down: both centred in 120px

    Check by hand: the 40px item leaves 80 pixels, half above, so it starts at 40; the 80px item leaves 40, so it starts at 20. Before flexbox, centring something up and down was famously awkward. Now two lines do it both ways at once: justify-content: center for the main axis and align-items: center for the cross axis.

    <!DOCTYPE html>
    <style>
      body { margin: 0; }
      .screen { display: flex; justify-content: center; align-items: center; width: 600px; height: 300px; background-color: lightyellow; }
      .badge { width: 100px; height: 50px; background-color: gold; }
    </style>
    <div class="screen"><div class="badge">Sale</div></div>

    Checked in Chrome

    • dead centre: 250 from the left and 125 from the top, in a 600 by 300 box

    align-self: one item its own way

    align-self, written on one item, overrides the container's align-items for that item alone.

    <!DOCTYPE html>
    <style>
      body { margin: 0; }
      .row { display: flex; align-items: flex-start; height: 120px; width: 600px; }
      .row div { width: 100px; height: 40px; background-color: gold; }
      .row .last { align-self: flex-end; }
    </style>
    <div class="row">
      <div>Rice</div>
      <div class="last">Dal</div>
    </div>

    Checked in Chrome

    • the first item at the top; the one with align-self: flex-end at the bottom, 80 down

    align-items with no height to work in

    align-items moves items inside the row's height. A row with no height of its own is exactly as tall as its tallest item, so centring the tallest item changes nothing. If align-items seems to do nothing, check whether the row has any spare height.

    Worked example 4

    A notice board is 600 by 200 pixels. Its single message box, 200 by 60, must sit exactly in the middle both ways. Write the rule and work out where the box's top-left corner lands.

    What we have: a 600 by 200 container and a 200 by 60 box

    What we need: a rule that centres it both ways, and its top-left corner

    The plan: justify-content: center for left and right; align-items: center for up and down

    1. Left: (600 − 200) ÷ 2 = 200.
    2. Top: (200 − 60) ÷ 2 = 70.
    <!DOCTYPE html>
    <style>
      body { margin: 0; }
      .board { display: flex; justify-content: center; align-items: center; width: 600px; height: 200px; }
      .message { width: 200px; height: 60px; background-color: gold; }
    </style>
    <div class="board"><div class="message">Fair on Saturday</div></div>

    Checked in Chrome

    • the box's corner is at 200 across and 70 down

    justify-content: center; align-items: center; the box's corner lands at 200 across, 70 down.

    Check: the browser placed the corner exactly where the arithmetic said.

    When you are stuck: align-items

    Remember the axes: in a row, align-items moves items up and down; justify-content moves them left and right.

    Cards of uneven height: the default stretch levels them, as long as they have no height set.

    Centring does nothing: the row may have no spare height; give it a height or min-height.

    Your turn

    What is the default value of align-items, and what does it do?Tap to reveal
    1. Cards come out level.

    stretch: items with no height fill the row's height.

    Which two lines centre a box both ways inside a flex container?Tap to reveal
    1. One for each axis.

    justify-content: center; and align-items: center;

    How do you move just one item to the bottom of the row?Tap to reveal
    1. A property on the item itself.

    align-self: flex-end on that item.

    Did you know?

    Equal heights, from the start

    Equal-height cards are built into flexbox. The 2012 Candidate Recommendation's own example of a shop page sets display: flex with the comment "Flex layout so items have equal height". It works because align-items starts as stretch, so an item with no height of its own fills the height of the row.

    Why it fits here: This topic's cards come out level for exactly this reason: stretch is the default.

    Sources: W3C: Flexible Box Layout, Candidate Recommendation 2012; W3C: CSS Flexible Box Layout

    Safe centring

    Centring can hide content. The Box Alignment standard warns that aligning exactly as asked can push an item out of its container and lose data: a centred sidebar's tall items might spill past the screen's start edge, where no one can scroll. So it adds the keyword safe. With align-items: safe center, an item that overflows is aligned to the start instead.

    Why it fits here: This topic centres with align-items: center; safe is the same idea with a guard for items too big to fit.

    Source: W3C: CSS Box Alignment Level 3

    In one line

    The align-items property lines items up along the cross axis: stretch by default, so cards come out level, or flex-start, center, flex-end, baseline. The align-self property overrides it for one item, and justify-content with align-items centres both ways.

    When the row is too long: flex-wrap

    At a glance

    Each item in a flex row asks for its width, but the row may be narrower than all of them together. Then, by default, the row squeezes them: every item shrinks so that all of them stay on one line, thin and crowded.

    With flex-wrap: wrap, the items that do not fit move onto a new line instead, at their own size, like passengers waiting for the next lift. The gap property then spaces both the items and the lines.

    Take a guess: If five 100px items sit in a 300px flex row with no wrapping, how wide does each one become?

    Five people try to stand in a lift built for three. They can squeeze, each taking less room, or the extra two can wait for the next trip. A flex row faces the same choice when its items do not fit, and by default it squeezes.

    By default, items shrink

    <!DOCTYPE html>
    <style>
      body { margin: 0; }
      .board { display: flex; width: 300px; }
      .stall { width: 100px; height: 40px; background-color: gold; }
    </style>
    <div class="board">
      <div class="stall">Rice</div>
      <div class="stall">Dal</div>
      <div class="stall">Atta</div>
      <div class="stall">Oil</div>
      <div class="stall">Salt</div>
    </div>

    Checked in Chrome

    • five 100px stalls in 300px: all squeezed to 60px each, on one line
    • still one line

    Each stall asked for 100 pixels, but the row has only 300 for five. Flex items are allowed to shrink below their width, so the browser shrank all five equally: 300 ÷ 5 = 60 each. On a phone, a menu of many items shrinks like this until its words no longer fit.

    flex-wrap: wrap

    flex-wrap: wrap, on the container, lets items that do not fit move onto a new line, keeping their size, like the next trip of the lift.

    <!DOCTYPE html>
    <style>
      body { margin: 0; }
      .board { display: flex; width: 300px; flex-wrap: wrap; }
      .stall { width: 100px; height: 40px; background-color: gold; }
    </style>
    <div class="board">
      <div class="stall">Rice</div>
      <div class="stall">Dal</div>
      <div class="stall">Atta</div>
      <div class="stall">Oil</div>
      <div class="stall">Salt</div>
    </div>

    Checked in Chrome

    • three stalls on the first line, two on the second
    • the second line starts 40px down
    • every stall keeps its 100px

    With gap on a wrapping container, the gap applies between lines too, as well as between items on a line. row-gap and column-gap set the two separately.

    <!DOCTYPE html>
    <style>
      body { margin: 0; }
      .board { display: flex; width: 300px; flex-wrap: wrap; gap: 10px; width: 320px; }
      .stall { width: 100px; height: 40px; background-color: gold; }
    </style>
    <div class="board">
      <div class="stall">Rice</div>
      <div class="stall">Dal</div>
      <div class="stall">Atta</div>
      <div class="stall">Oil</div>
      <div class="stall">Salt</div>
    </div>

    Checked in Chrome

    • 10px between neighbours: three fit in 320px (100 + 10 + 100 + 10 + 100)
    • and 10px between the lines

    A memory aid

    Squeeze or wrap. A flex row squeezes its items onto one line unless you say flex-wrap: wrap; then the extra items move to a new line, keeping their size.

    A wrapping row of cards is the easiest way to make a page that works on any screen. It shows three cards in a row on a laptop, two on a tablet and one on a phone, with no other rule. The responsive design lesson builds on exactly this.

    Worked example 5

    A shop shows eight product cards, each 200px wide, with 16px gaps, in a box that is 650px wide on a laptop. How many fit on each line, and how many lines are there?

    What we have: eight 200px cards, 16px gaps, a 650px box, wrapping

    What we need: the cards per line and the number of lines

    The plan: add cards and gaps until the next card would not fit; then divide eight by that

    1. Two cards: 200 + 16 + 200 = 416. Three: 416 + 16 + 200 = 632, which fits in 650. Four would need 848: too much.
    2. So three cards fit on a line.
    3. Eight cards at three a line: 3, 3 and 2, so three lines.
    <!DOCTYPE html>
    <style>
      body { margin: 0; }
      .shop { display: flex; flex-wrap: wrap; gap: 16px; width: 650px; }
      .card { width: 200px; height: 60px; background-color: gold; }
    </style>
    <div class="shop"><div class="card">Rice</div><div class="card">Dal</div><div class="card">Atta</div><div class="card">Oil</div><div class="card">Salt</div><div class="card">Tea</div><div class="card">Sugar</div><div class="card">Ghee</div></div>

    Checked in Chrome

    • the cards fall on three lines
    • three on the first line

    Three cards a line, on three lines (3, 3 and 2).

    Check: the browser placed the eight cards on three distinct lines, three on the first.

    A path that fails: Leaving out flex-wrap. All eight cards then squeeze onto one 650px line, each about 67px wide, too narrow for a product name.

    When you are stuck: wrapping

    Items squeezed too thin: add flex-wrap: wrap to the container.

    Items that will not shrink and overflow instead: they may have flex-shrink: 0 or a min-width; the next section explains.

    Spacing between lines too: gap works on both, or set row-gap alone.

    Your turn

    By default, what does a flex row do when its items do not fit?Tap to reveal
    1. Squeeze or wrap?

    It squeezes them: the items shrink to fit one line.

    Which declaration lets the items move onto a new line?Tap to reveal
    1. On the container.

    flex-wrap: wrap.

    Six 100px items wrap in a 350px container with no gap. How many fit on the first line?Tap to reveal
    1. Add 100s until the next would not fit.

    Three (300px; a fourth would need 400).

    Did you know?

    Shrink yes, grow no

    The squeezing in this topic is the default on purpose. The Flexbox standard starts every item at flex: 0 1 auto, which means grow 0, shrink 1 and basis auto. So an item never grows into spare space unless asked, but it is allowed to shrink to its minimum size when there is not enough space.

    Why it fits here: It explains why this topic's row of five items shrinks them instead of wrapping.

    Source: W3C: CSS Flexible Box Layout

    Why a flex item stops shrinking

    A flex item stops shrinking at the size of its content. The Flexbox standard gives min-width a new starting value, auto, and for a flex item that means a content-based minimum size. So one long word or a wide picture keeps its item from shrinking further, and the row overflows. Setting min-width: 0 on the item removes that floor.

    Why it fits here: It is the limit on this topic's squeezing: items shrink, but not below their content.

    Source: W3C: CSS Flexible Box Layout

    In one line

    A flex row squeezes its items onto one line by default. With flex-wrap: wrap, the extra items move onto new lines at their own size, and gap spaces both the items and the lines.

    Sizing the items: grow, shrink and basis

    At a glance

    Three friends share a taxi, and the one who went twice as far pays twice as much. Flex items share a row's spare space in the same way. The flex-grow property says how many shares an item takes, flex-shrink says how much it gives way, and flex-basis sets its starting size.

    The shorthand flex: 1 on every item makes equal columns. An auto margin pushes an item to the far end of the row. The order property moves items on the screen, but only on the screen: the HTML order stays the same.

    Take a guess: If one item has flex-grow: 2 and another has flex-grow: 1, how is 300px of spare space shared?

    Three friends share a 600 rupee taxi ride, but one of them went twice as far. Splitting it equally would be unfair; splitting it by distance is fair. Flex items share a row's spare space the same way: each one says how big a share it wants.

    flex-grow: sharing the spare space

    flex-grow is a number saying how many shares of the spare space an item takes. The default is 0: no share, the item stays at its width.

    <!DOCTYPE html>
    <style>
      body { margin: 0; }
      .row { display: flex; width: 600px; }
      .row > div { width: 100px; height: 40px; background-color: gold; }
      .a { flex-grow: 1; }
      .b { flex-grow: 2; }
    </style>
    <div class="row">
      <div class="a">A</div>
      <div class="b">B</div>
      <div>C</div>
    </div>

    Checked in Chrome

    • A takes 1 share and B 2 shares of the 300 spare pixels: 200, 300, and C stays at 100

    Work it out. The three items need 300 pixels, so 300 are spare. There are 1 + 2 = 3 shares, so one share is 100 pixels. A gets one share, 100 + 100 = 200; B gets two, 100 + 200 = 300; C asked for none and stays at 100.

    flex-shrink: giving way when space runs out

    flex-shrink is the opposite: how much an item gives way when the row is too small. The default is 1, so all items shrink together, as the wrap section saw. flex-shrink: 0 means "never shrink me", which suits a logo or an icon.

    <!DOCTYPE html>
    <style>
      body { margin: 0; }
      .row { display: flex; width: 250px; }
      .row > div { width: 100px; height: 40px; background-color: gold; }
      .logo { flex-shrink: 0; }
    </style>
    <div class="row">
      <div>Menu</div>
      <div>Search</div>
      <div class="logo">Logo</div>
    </div>

    Checked in Chrome

    • in 250px, the two shrinking items give way to 75 each; the logo keeps its 100

    flex-basis and the flex shorthand

    flex-basis is the size an item starts from before the sharing, used instead of width along the main axis. The three are usually written together, in this order, as flex:

    You writeMeansUse it for
    flex: 1grow 1, shrink 1, start from 0: share the whole row equallyequal columns, whatever their content
    flex: 2the same, with two sharesa column twice as wide as its flex: 1 neighbours
    flex: nonegrow 0, shrink 0, start from its own sizesomething that must keep its size, such as an icon
    flex: 0 0 200pxgrow 0, shrink 0, start at 200pxa fixed sidebar
    <!DOCTYPE html>
    <style>
      body { margin: 0; }
      .row { display: flex; width: 600px; }
      .row > div { width: 100px; height: 40px; background-color: gold; }
      .cols > div { flex: 1; }
    </style>
    <div class="row cols">
      <div>Short</div>
      <div>A much longer piece of text in the middle column</div>
      <div>Short</div>
    </div>

    Checked in Chrome

    • flex: 1 on all three: exactly equal columns of 200, though the middle one holds far more text

    flex: 1 starts every item from 0 and shares all the space equally, so the columns are equal whatever is inside them. That makes it the usual way to build equal columns.

    An auto margin pushes an item aside

    Lesson 3's auto margins share leftover space. In a flex row, margin-left: auto on one item takes all the leftover space to its left, pushing that item and everything after it to the far end. It is the classic way to put a cart at the right of a top bar.

    <!DOCTYPE html>
    <style>
      body { margin: 0; }
      .row { display: flex; width: 600px; }
      .row > div { width: 100px; height: 40px; background-color: gold; }
      .cart { margin-left: auto; }
    </style>
    <div class="row">
      <div>Logo</div>
      <div>Menu</div>
      <div class="cart">Cart</div>
    </div>

    Checked in Chrome

    • the logo and menu stay left; the cart is pushed to the right end, at 500

    order: moving items on screen only

    order changes where an item is drawn: lower numbers first, the default being 0. It does not change the HTML, so screen readers and the Tab key still follow the HTML's order.

    <!DOCTYPE html>
    <style>
      body { margin: 0; }
      .row { display: flex; width: 600px; }
      .row > div { width: 100px; height: 40px; background-color: gold; }
      .first { order: 2; }
    </style>
    <div class="row">
      <div class="first">Offers</div>
      <div>Home</div>
    </div>

    Checked in Chrome

    • on screen, Offers is drawn second, at 100
    • but in the HTML, and for the Tab key, it is still first

    Reordering the meaning

    Using order to put a page's parts in a different sequence from its HTML means sighted mouse users and keyboard or screen reader users meet the page in different orders. Keep order for small visual touches; if the sequence matters, change the HTML.

    Worked example 6

    A product row has an image box that must stay 120px, a description that should take all the remaining space, and a price that must stay 80px. The row is 600px. Write the three rules and work out the description's width.

    What we have: two fixed items and one that fills the rest

    What we need: flex values for each, and the description's width

    The plan: the image and the price: flex: none with their widths; the description: flex: 1

    1. The fixed items take 120 + 80 = 200 pixels.
    2. The description takes the rest: 600 − 200 = 400 pixels.
    <!DOCTYPE html>
    <style>
      body { margin: 0; }
      .product { display: flex; width: 600px; }
      .pic { flex: none; width: 120px; }
      .desc { flex: 1; }
      .price { flex: none; width: 80px; }
    </style>
    <div class="product">
      <div class="pic">Photo</div>
      <div class="desc">Toor dal, 1 kg, unpolished</div>
      <div class="price">₹180</div>
    </div>

    Checked in Chrome

    • 120 for the picture, 400 for the description, 80 for the price

    .pic and .price: flex: none with their widths; .desc: flex: 1. The description is 400px.

    Check: the browser drew the three at 120, 400 and 80 pixels.

    When you are stuck: sizing items

    Equal columns: flex: 1 on each. One column twice as wide: flex: 2 on it.

    Something that must keep its size: flex: none, or flex-shrink: 0.

    Push an item to the far end: margin-left: auto on it.

    Your turn

    Two items have flex-grow 1 and 3, and there are 400 spare pixels. How many does each get?Tap to reveal
    1. 4 shares of 100.

    100 and 300.

    What does flex: 1 mean in full?Tap to reveal
    1. Three values.

    Grow 1, shrink 1, start from 0: share the row equally.

    Does order change the order the Tab key follows?Tap to reveal
    1. What does order change?

    No: only where items are drawn.

    Did you know?

    flex: 1 means grow from zero

    flex: 1 is short for three values: grow 1, shrink 1 and a basis of zero. The Flexbox standard says this pattern sets the flex basis to zero, so each item gets its share of the free space. Because every item then starts from nothing, the whole row is shared out by the grow numbers, and equal numbers give equal columns.

    Why it fits here: This topic's equal columns come from this rule: each item starts at zero and takes one equal share.

    Source: W3C: CSS Flexible Box Layout

    Seen in one order, read in another

    Moving items with order changes only what the eye sees. The Flexbox standard says it leaves the source order intact for speech and for moving through the page with the keyboard. So it warns that authors must not use order, or the reverse directions, as a substitute for correct source order, because that can ruin the accessibility of the document.

    Why it fits here: This topic's order moves items on the screen only; this is the standard's own warning about it.

    Source: W3C: CSS Flexible Box Layout

    In one line

    flex-grow shares spare space by shares, flex-shrink says how much an item gives way, flex-basis is its starting size, and flex: 1 makes equal columns. An auto margin pushes an item to the far end, and order moves items on screen only.

    Where it is used

    Most of the rows on any page you use are flex rows.

    What you learnedWhere it is usedA real example
    display: flextop bars, menus, button groupsa news site's menu: a ul made into a row with one rule
    justify-content: space-betweenheaders with items at both endsa logo at the left and a search box at the right of a shop's header
    margin-left: autopushing one item awaythe cart icon at the far right of a top bar
    align-items: centerlining up icons and wordsan icon and its label centred on one line in a settings list
    stretch (the default)rows of cardsproduct cards in a row that come out the same height
    flex-wrap: wrapcard grids that fit any screena page of product cards: three a line on a laptop, one on a phone
    flex: 1equal columns, and "take the rest"a search box that fills the space between a logo and a button
    flex-direction: columnstacks with gapsa form's label and box stacked, with a gap between

    Mistakes and debugging

    These are the flexbox slips everyone makes, each measured in the browser.

    1. display: flex on the items, not the container

    <!DOCTYPE html>
    <style>
      body { margin: 0; }
      .stall { display: flex; width: 100px; height: 40px; }
    </style>
    <div class="board">
      <div class="stall">Rice</div>
      <div class="stall">Dal</div>
    </div>

    Checked in Chrome

    • (the slip: the stalls still stack, because their parent is not a flex container)

    The fix: .board { display: flex; }. The rule goes on the parent.

    2. justify and align swapped in a column

    <!DOCTYPE html>
    <style>
      body { margin: 0; }
      .col { display: flex; flex-direction: column; justify-content: center; height: 200px; width: 600px; }
      .col div { width: 100px; height: 40px; }
    </style>
    <div class="col"><div>Centred?</div></div>

    Checked in Chrome

    • (the surprise: in a column, justify-content centres up and down, 80 from the top, while the box stays at the left)

    In a column the main axis runs downwards, so justify-content works up and down and align-items left and right. The fix: think in axes, not in directions: main axis, justify; cross axis, align.

    3. A row squeezed instead of wrapped

    Many items on a phone shrink until their text no longer fits. The fix: flex-wrap: wrap.

    4. A width that seems to be ignored

    A flex item with width: 200px comes out narrower: it is shrinking, because flex-shrink is 1 by default. The fix: flex-shrink: 0 (or flex: none) on the item, or let the row wrap.

    5. order used to change the meaning

    The page reads one way on screen and another way with the Tab key. The fix: change the order in the HTML; keep order for small touches.

    6. align-items with no room

    Centring items in a row that is only as tall as its tallest item changes nothing. The fix: give the row a height or a min-height.

    The debugging corner: the flex badge

    In DevTools' Elements panel, a flex container has a small flex badge beside its tag. Click it, and the page draws the container's outline, its items, its gaps and its free space. In the Styles pane, a small icon beside display: flex opens an editor with buttons for every justify-content and align-items value, so you can try each and watch the row change.

    Quick card

    The lesson on one card.

    Every idea of the lesson

    <!DOCTYPE html>
    <style>
      body { margin: 0; }
      .bar { display: flex; align-items: center; gap: 10px; width: 600px; height: 60px; }
      .bar .cart { margin-left: auto; }
      .bar div { width: 80px; height: 30px; background-color: gold; }
      .cards { display: flex; flex-wrap: wrap; gap: 10px; width: 600px; }
      .cards .card { flex: 1 1 180px; height: 50px; background-color: lightyellow; }
    </style>
    <div class="bar">
      <div>Logo</div>
      <div>Menu</div>
      <div class="cart">Cart</div>
    </div>
    <div class="cards">
      <div class="card">Rice</div>
      <div class="card">Dal</div>
      <div class="card">Atta</div>
      <div class="card">Oil</div>
    </div>

    Checked in Chrome

    • the bar: logo and menu with a 10px gap, the cart pushed to the right end
    • all centred in the 60px bar: 15 from the top
    • the four cards, at least 180px each, wrap onto two lines
    • the first line's three share it equally; the last card grows to fill its own line
    IdeaIn one line
    display: flexon the container; its direct children become items in a row
    the two axesmain: the items' direction (justify); cross: across it (align)
    flex-directionrow (default) or column
    justify-contentflex-start, flex-end, center, space-between, space-around, space-evenly
    gapa fixed space between neighbours, and between lines when wrapping
    align-items, align-selfstretch (default), flex-start, center, flex-end, baseline
    flex-wrap: wrapextra items move to new lines instead of squeezing
    flex: 1, flex: noneshare the space equally; keep its own size
    margin-left: autopush an item to the far end
    ordermoves items on screen only; never for meaning

    The story: The row places itself

    You give the board one rule: lay your notices in a row. Then you tell the row how to share its space: equal gaps between the notices, all of them the same height, their price lines along the bottom.

    On the palm-sized panel, the row no longer runs off the edge. It wraps, and the last notices move onto a second line, still evenly spaced. Nobody nudged anything.

    The warden opens the board on three different panels, one after another. "It rearranges itself," he says, and Corin quietly deletes his margins.

    Reagents gathered: flex container, flex item, justify-content, align-items, gap, flex-wrap.

    Sources

    • MDN Web Docs (Prose CC BY-SA 2.5 or later; code samples added since 2010-08-20 CC0 (its licensing page, read 2026-10-26); reused with credit)
    • HTML Living Standard (WHATWG) (CC BY 4.0: "Copyright WHATWG (Apple, Google, Mozilla, Microsoft). This work is licensed under a Creative Commons Attribution 4.0 International License" (its acknowledgements page, read 2026-10-26); reused with credit)