Chapter 19 of 33

Flexbox

For years, simple layout tasks in CSS were surprisingly hard. Vertically centring a box needed tricks. Making three columns the same height needed hacks. Putting a logo on the left and links on the right meant floats and clearfixes (see Float & Clear). Flexbox (the Flexible Box Layout module) solved all of these.

Flexbox is a one-dimensional layout system: it arranges items in a single row or a single column, and decides how to share out the free space between them. In this chapter we learn every Flexbox property, how the browser calculates item sizes (a favourite interview topic), and the mistakes that trip people up. In the next chapter, Flexbox Layout Patterns, we'll use it to build real components.


The Flex Container and Flex Items

An element with display: flex (or inline-flex) becomes a flex container. Its direct children become flex items, which are laid out along one line (or several lines, if wrapping is allowed) using the flex layout algorithm.

<div class="container">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
</div>
.container {
  display: flex;
}

With just that one line, the three divs — which would normally stack vertically — sit side by side in a row, each as wide as its content, and all as tall as the tallest one.

  • Only direct children become flex items. Grandchildren are laid out normally inside their own parent.

  • display: flex makes the container itself block-level (it takes the full width). display: inline-flex makes the container sit inline like a word, sized to its content. The items behave the same in both.

  • float and clear have no effect on flex items, and vertical-align is ignored for them.


The Two Axes

Everything in Flexbox is described in terms of two axes, not "horizontal" and "vertical":

  • The main axis is the direction the items are placed in. Properties starting with justify- work along it.

  • The cross axis is perpendicular to it. Properties starting with align- work along it.

flex-direction: row  (default)

 main start                                 main end
     │                                          │
     ▼        main axis  ────────────────►      ▼
   ┌────────┬────────┬────────┬─────────────────┐  ◄ cross start
   │ item 1 │ item 2 │ item 3 │   free space    │   │ cross
   │        │        │        │                 │   │ axis
   └────────┴────────┴────────┴─────────────────┘  ▼ cross end

When you change flex-direction to column, the main axis becomes vertical and the cross axis becomes horizontal. That's why justify-content: center centres horizontally in a row but vertically in a column. If you always think "main axis" and "cross axis", you'll never get confused.


Container Properties

flex-direction

ValueMain axis runs
row (default)In the text direction (left → right in English)
row-reverseOpposite to the text direction
columnTop → bottom
column-reverseBottom → top

The -reverse values only change the visual order. Screen readers and the Tab key still follow the HTML order, so don't use them to reorder meaningful content.

flex-wrap

By default (nowrap) all items are forced into one line, shrinking if necessary — and overflowing if they can't shrink enough. wrap lets items move onto new lines; wrap-reverse stacks new lines in the opposite cross direction.

.container {
  display: flex;
  flex-wrap: wrap;
}

flex-flow is a shorthand for both: flex-flow: row wrap;

justify-content (main axis)

Decides what to do with the free space left on the main axis after the items are sized. Below, the container is 500px wide and holds three 100px items, so there is 200px of free space. These positions were measured in Chrome:

ValueWhat happens to the 200pxItem x-positions
flex-start (the default normal acts like this)All at the end0, 100, 200
flex-endAll at the start200, 300, 400
centerHalf on each side (100 + 100)100, 200, 300
space-betweenDivided between items only: 2 gaps of 1000, 200, 400
space-aroundEach item gets 200 ÷ 3 ≈ 66.67 split around it: 33.33 at each edge, 66.67 between items33.33, 200, 366.67
space-evenly4 equal gaps of 50 (edges included)50, 200, 350
space-between  [1]------[2]------[3]
space-around   -[1]--[2]--[3]-        (edge gap = half the middle gap)
space-evenly   --[1]--[2]--[3]--      (all gaps equal)

align-items (cross axis)

Aligns items inside their line along the cross axis.

ValueEffect
stretch (default behaviour)Items stretch to fill the line's cross size — that's why flex items in a row are all equally tall. Only works if the item has no fixed height.
flex-startItems sit at the cross start (top, in a row)
flex-endItems sit at the cross end (bottom, in a row)
centerItems are centred on the cross axis
baselineItems are lined up so the first line of text in each shares a baseline — useful when items have different font sizes

align-content (multi-line only)

When items wrap onto several lines and the container has extra cross-axis space, align-content distributes the lines (like justify-content does for items). It accepts flex-start, flex-end, center, space-between, space-around, space-evenly and stretch (default behaviour). It has no effect on a single-line container (flex-wrap: nowrap).

Remember: align-items positions items within their line; align-content positions the lines within the container.

gap

gap puts fixed space between items (never at the outer edges) — no more margin tricks. gap: 10px 20px means 10px between rows and 20px between columns; row-gap and column-gap set them individually. It's supported for flexbox in all modern browsers.

.container {
  display: flex;
  gap: 20px;
}

The gap is reserved before free space is shared: with three flex: 1 items in a 500px container and gap: 20px, each item gets (500 − 2 × 20) ÷ 3 ≈ 153.33px. We measured exactly that.


Item Properties

order

Items are placed in increasing order value (default 0); equal values keep source order. order: -1 moves an item to the front. Like row-reverse, it changes only the visual order — the tab order and reading order still follow the HTML.

align-self

Overrides the container's align-items for one item. For example, in a row of items aligned to the top, align-self: flex-end puts one item at the bottom.

There is no justify-self in Flexbox (it is ignored on flex items). To push one item along the main axis, use auto margins — explained below.

flex-grow, flex-shrink and flex-basis

These three decide how big each item is along the main axis. They are the heart of Flexbox.

PropertyMeaningDefault
flex-basisThe item's starting size on the main axis, before free space is shared out. auto means "use my width (in a row) or height (in a column), or my content size if that is auto".auto
flex-growHow many "shares" of the positive free space the item takes. 0 = don't grow.0
flex-shrinkHow strongly the item shrinks when there is negative free space (overflow). 0 = never shrink.1

So by default, items don't grow but can shrink.


How the Browser Calculates Sizes

The algorithm, simplified:

  1. Find each item's flex base size (from flex-basis).

  2. Free space = container's inner main size − sum of base sizes − gaps − item margins/borders/padding.

  3. If free space is positive: share it in proportion to flex-grow.

  4. If free space is negative: remove it in proportion to flex-shrink × flex-basis.

  5. Clamp any item that violates its min-width/max-width, then share the remaining space among the others again.

Worked example 1: growing

.container { display: flex; width: 600px; }
.a { flex: 1 1 100px; }   /* grow 1, shrink 1, basis 100px */
.b { flex: 2 1 200px; }   /* grow 2, shrink 1, basis 200px */
.c { flex: 1 1 100px; }
Sum of bases   = 100 + 200 + 100 = 400px
Free space     = 600 − 400 = +200px   (positive → grow)
Total grow     = 1 + 2 + 1 = 4 shares
One share      = 200 ÷ 4 = 50px

a = 100 + 1 × 50 = 150px
b = 200 + 2 × 50 = 300px
c = 100 + 1 × 50 = 150px          total = 600px ✓

Measured in Chrome: 150px, 300px, 150px.

Note: b is twice as wide as a here, but that's partly because of its bigger basis. flex-grow: 2 does not mean "twice as wide"; it means "gets twice as much of the extra space".

Worked example 2: shrinking

.container { display: flex; width: 400px; }
.a { flex: 0 1 300px; }
.b { flex: 0 1 200px; }
Sum of bases   = 300 + 200 = 500px
Free space     = 400 − 500 = −100px   (negative → shrink)
Weights        = shrink × basis:  a = 1 × 300 = 300,  b = 1 × 200 = 200
Total weight   = 500

a loses 100 × 300/500 = 60px  → 240px
b loses 100 × 200/500 = 40px  → 160px

Measured in Chrome: 240px and 160px. Shrinking is weighted by the basis, so bigger items give up more pixels — fair, since they have more to lose.

Now change a to flex-shrink: 2: weights become a = 2 × 300 = 600, b = 1 × 200 = 200, total 800. a loses 100 × 600/800 = 75px → 225px; b loses 25px → 175px. Chrome agrees.

Worked example 3: min/max limits

.container { display: flex; width: 600px; }
.item { flex: 1; }
.middle { max-width: 100px; }

All three would get 200px, but the middle one can't exceed 100px. It is frozen at 100px and the remaining 500px is shared between the other two: 250px, 100px, 250px (measured).


The flex Shorthand

Always prefer the flex shorthand: flex: <grow> <shrink> <basis>. The common keyword forms are worth memorising:

ShorthandExpands toBehaviour
flex: initial0 1 autoThe default: sized by width/content, can shrink, won't grow
flex: auto1 1 autoStarts from width/content size, then grows/shrinks
flex: none0 0 autoRigid: exactly its width/content size
flex: 11 1 0%Ignores content size; all flex: 1 items share space equally
flex: 22 1 0%Twice the share of a flex: 1 sibling
flex: 200px1 1 200pxGrows/shrinks from a 200px start

Watch out: a single number sets the basis to 0, not auto. So flex: 1 and flex-grow: 1 are different! flex-grow: 1 alone keeps the default basis auto.

flex: 1 vs flex: auto

.container { display: flex; width: 600px; }
.a { width: 100px; }
.b { width: 300px; }
With flex: auto  (basis = width)
  bases 100 + 300 = 400, free = 200, each gets 100
  a = 200px, b = 400px          ← keeps the size difference

With flex: 1     (basis = 0)
  bases 0 + 0 = 0, free = 600, each gets 300
  a = 300px, b = 300px          ← equal columns

Use flex: 1 when you want equal columns, flex: auto when you want items to keep their natural proportions and soak up extra space.


Auto Margins: The Secret Weapon

In a flex container, a margin set to auto absorbs all free space in that direction — before justify-content is applied.

<nav class="navbar">
  <a href="/">Home</a>
  <a href="/courses">Courses</a>
  <a href="/login" class="login">Login</a>
</nav>
.navbar {
  display: flex;
  gap: 16px;
}

.login {
  margin-left: auto;    /* push this item (and anything after it) to the far right */
}

And margin: auto on a single item inside a flex container centres it on both axes.


The min-width: auto Trap

Flex items have a hidden default: min-width: auto (in a row; min-height: auto in a column). It means "don't shrink below my content's minimum size" — for text, that's the longest unbreakable word.

.container { display: flex; width: 300px; }
.item { flex: 1; }

If one item contains a long URL or a long word, it can't shrink below that word's width. In our test (default 16px serif font), an item holding a 66-letter word ("xxxx…x") ended up 528px wide inside a 300px container, overflowing it and squeezing its sibling down to the width of its own text — even though flex: 1 should have made the two equal. With min-width: 0 added (below), both items became exactly 150px.

The fix is to allow the item to shrink, and let the text break:

.item {
  flex: 1;
  min-width: 0;              /* allow shrinking below content size */
  overflow-wrap: anywhere;   /* let long words break */
}

This is a very common real bug: a long filename or <pre> block blowing up a flex layout. Remember: overflowing flex item → try min-width: 0.


A Complete Example

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Flexbox Demo</title>
  <style>
    body {
      font-family: sans-serif;
      margin: 20px;
    }

    .plans {
      display: flex;
      gap: 16px;
      align-items: stretch;      /* equal heights (the default) */
    }

    .plan {
      flex: 1;                   /* three equal columns */
      display: flex;             /* a plan is ALSO a flex container */
      flex-direction: column;
      border: 2px solid #94a3b8;
      border-radius: 8px;
      padding: 16px;
    }

    .plan.popular {
      border-color: #2563eb;
      order: -1;                 /* visually first */
    }

    .plan button {
      margin-top: auto;          /* push the button to the bottom */
      padding: 8px;
    }
  </style>
</head>
<body>
  <div class="plans">
    <div class="plan">
      <h3>Free</h3>
      <p>All tutorials.</p>
      <button>Start</button>
    </div>
    <div class="plan popular">
      <h3>Pro</h3>
      <p>Notes, mock tests, interview questions and a resume review.</p>
      <p>Most popular with final-year students.</p>
      <button>Buy</button>
    </div>
    <div class="plan">
      <h3>GATE Pack</h3>
      <p>Previous-year questions.</p>
      <button>Buy</button>
    </div>
  </div>
</body>
</html>

What you will see: three cards of exactly equal width and equal height side by side. The blue-bordered "Pro" card appears first (on the left) because of order: -1, even though it is second in the HTML. It has the most text, so it decides the row's height; the other two cards stretch to match. In every card the button sits at the very bottom, so all three buttons line up, thanks to margin-top: auto inside the column flex container. The buttons also stretch to the full width of their card: in a column, the cross axis is horizontal, and the default align-items: stretch stretches them along it (add align-self: flex-start to a button if you want it narrow).


Flexbox Cheat Sheet

On the containerOn the items
display: flex | inline-flexflex: grow shrink basis
flex-directionflex-grow / flex-shrink / flex-basis
flex-wrap / flex-floworder
justify-content (main axis)align-self (cross axis)
align-items (cross axis, per line)margin: auto tricks
align-content (lines, when wrapping)min-width: 0 fix
gap / row-gap / column-gap

Common Mistakes

  • Putting justify-content or align-items on the items. They belong on the container.

  • Thinking justify-content is always horizontal. It follows the main axis, which is vertical with flex-direction: column.

  • Vertical centring doesn't work in a column. A column container without a height is only as tall as its content, so there's no free space to centre in. Give it a height (e.g. min-height: 100vh).

  • Mixing up flex: 1 and flex-grow: 1. They have different bases (0% vs auto).

  • Long words overflowing because of min-width: auto. Add min-width: 0.

  • Using order or row-reverse for meaningful reordering. Keyboard and screen reader users still get the HTML order.

  • Expecting align-content to work without wrapping. It only affects multi-line containers.


Interview / Exam Questions

1. What is the difference between the main axis and the cross axis?

The main axis is the direction set by flex-direction along which items are placed (horizontal for row, vertical for column). The cross axis is perpendicular to it. justify-content aligns along the main axis; align-items, align-self and align-content along the cross axis.

2. A 600px flex container has items with flex: 1 1 100px, flex: 2 1 200px and flex: 1 1 100px. What are their widths?

Bases sum to 400px, leaving 200px free. Total grow factor is 4, so one share is 50px. Widths: 100 + 50 = 150px, 200 + 100 = 300px, 100 + 50 = 150px.

3. Two items with flex: 0 1 300px and flex: 0 1 200px are in a 400px container. What are their widths?

They overflow by 100px. Shrink is weighted by flex-shrink × basis: 300 and 200 (total 500). The first loses 60px (→ 240px), the second loses 40px (→ 160px).

4. What does flex: 1 expand to? How does it differ from flex: auto?

flex: 1 is 1 1 0%; flex: auto is 1 1 auto. With flex: 1, the basis is zero, so all free space is shared equally and items become equal-sized regardless of content. With flex: auto, items start from their width/content size and only the leftover space is shared, so bigger items stay bigger.

5. What is the difference between align-items and align-content?

align-items aligns the items within each flex line on the cross axis. align-content distributes the flex lines themselves within the container's cross axis, and only has an effect when the container is multi-line (wrapping) and has extra cross-axis space.

6. How do you centre a div horizontally and vertically with Flexbox?

On the parent: display: flex; justify-content: center; align-items: center; — and make sure the parent has a height larger than the child (for example min-height: 100vh). Alternatively, display: flex on the parent and margin: auto on the child.

7. A flex item with a long URL overflows the container even though it has flex: 1. Why, and how do you fix it?

Flex items default to min-width: auto, which stops them shrinking below their min-content width (the long URL). Set min-width: 0 on the item (and let the text break with overflow-wrap: anywhere, or hide it with overflow: hidden).


Summary

  • display: flex turns direct children into flex items laid out along a main axis; the cross axis is perpendicular.

  • Container: flex-direction, flex-wrap, justify-content, align-items, align-content, gap.

  • Items: flex-grow, flex-shrink, flex-basis (via flex), order, align-self.

  • Positive free space is shared by grow factors; overflow is removed by shrink × basis.

  • flex: 1 = 1 1 0% (equal columns); flex: auto = 1 1 auto; flex: none = 0 0 auto.

  • Auto margins absorb free space — great for pushing items apart.

  • Overflowing items are usually fixed with min-width: 0.

You now know the tools. In Flexbox Layout Patterns we'll combine them into navbars, sticky footers, card grids, media objects and more.