Chapter 20 of 33

Flexbox Layout Patterns

In the Flexbox chapter we learned every property and how the browser calculates item sizes. Knowing the properties is one thing; knowing which combination to reach for when you see a design is another. Experienced developers don't think "justify-content, align-items, flex-grow…" — they think "that's a navbar", "that's a media object", "that's a sticky footer", and type the pattern from memory.

This chapter is a collection of those patterns. For each one we look at the design problem, the HTML, the CSS, and — most importantly — why each line is there. All of these were rendered in Chrome to confirm the result.


Pattern 1: Perfect Centering

Problem: centre a box (a login form, a loading spinner, an "empty cart" message) both horizontally and vertically.

.center-screen {
  display: flex;
  justify-content: center;   /* main axis (horizontal in a row) */
  align-items: center;       /* cross axis (vertical in a row) */
  min-height: 100vh;         /* there must be space to centre in */
}

Why min-height? A block element is only as tall as its content. Without extra height there's no free space on the cross axis, so "centre vertically" has nothing to do. min-height (instead of height) lets the container grow if the content is taller than the screen.

On phones, 100vh can be slightly taller than the visible area because of the browser's address bar. The newer unit 100dvh ("dynamic viewport height", see CSS Units) tracks the visible area and is supported in all current major browsers.

The shortest version is display: flex on the parent and margin: auto on the child — the auto margins swallow free space on all four sides.


Pattern 2: Navigation Bar

Problem: logo on the left, links on the right, everything vertically centred.

<header class="navbar">
  <a class="logo" href="/">CSLP</a>
  <nav class="links">
    <a href="/tutorials">Tutorials</a>
    <a href="/gate">GATE</a>
    <a href="/login">Login</a>
  </nav>
</header>
.navbar {
  display: flex;
  justify-content: space-between;  /* logo far left, nav far right */
  align-items: center;             /* vertical centring of both */
  flex-wrap: wrap;                 /* on tiny screens, nav moves below logo */
  gap: 12px;
  padding: 12px 20px;
}

.links {
  display: flex;                   /* the nav is ALSO a flex container */
  gap: 20px;
}
┌──────────────────────────────────────────────────┐
│ CSLP                       Tutorials  GATE  Login │
└──────────────────────────────────────────────────┘

Two ideas to notice:

  • Nesting flex containers. .links is a flex item of .navbar and at the same time a flex container for the three links. Real layouts are almost always nested like this.

  • space-between with two items puts one at each end. If you had three groups (logo, search box, links), space-between spreads them out with the middle one in between.

Variation: push only the last item

If the links should sit next to the logo and only "Login" goes to the far right, use an auto margin instead:

.navbar { display: flex; align-items: center; gap: 20px; }
.navbar .login { margin-left: auto; }

The auto margin eats all the free space to the left of "Login", pushing it (and anything after it) to the end.


Problem: on a page with little content, the footer floats up into the middle of the screen. We want it at the bottom of the window when the content is short, and after the content when the content is long.

<body>
  <header>Header</header>
  <main>Short content</main>
  <footer>© 2026 CS Learning Portal</footer>
</body>
body {
  display: flex;
  flex-direction: column;   /* stack header, main, footer vertically */
  min-height: 100vh;        /* at least one screen tall */
  margin: 0;
}

main {
  flex: 1;                  /* main takes all the leftover height */
}

Why it works: the body is a column flex container at least as tall as the viewport. The header and footer keep their natural height, and main grows to fill the remaining vertical space, which pushes the footer down to the bottom. When content is longer than the screen, there is no free space, main just takes its content height, and the footer comes after it normally.

(Note margin: 0: the default 8px body margin plus 100vh would otherwise create a scrollbar. Margins and the box model were covered in The Box Model.)


Pattern 4: Media Object

Problem: an image (avatar, thumbnail, icon) on one side and text on the other — comments, notifications, chat messages, search results. This used to be done with floats (see Float & Clear).

<div class="media">
  <img class="media-img" src="avatar.png" alt="Neha" width="56" height="56">
  <div class="media-body">
    <strong>Neha</strong>
    <p>Can someone explain why flex: 1 makes equal columns?</p>
  </div>
</div>
.media {
  display: flex;
  align-items: flex-start;  /* image stays at the top, not stretched */
  gap: 12px;
}

.media-img {
  flex: none;               /* never shrink or grow: stays 56×56 */
  border-radius: 50%;
}

.media-body {
  flex: 1;                  /* text takes the remaining width */
  min-width: 0;             /* allow it to shrink below its longest word */
  overflow-wrap: anywhere;  /* and let long words/URLs break onto new lines */
}

Each line has a job:

  • align-items: flex-start — with the default stretch, an image without a fixed height would be stretched to the full height of the text. Starting at the top keeps it square.

  • flex: none on the image — otherwise, with a long comment, the default flex-shrink: 1 squeezes the avatar into an oval.

  • min-width: 0 and overflow-wrap: anywhere on the body — the min-width: auto trap from the Flexbox chapter. Without min-width: 0, a long URL makes the body refuse to shrink and the whole media object grows wider than its container. min-width: 0 fixes the layout, and overflow-wrap lets the URL break so the text doesn't spill out of the box.

Want the image on the right? Add flex-direction: row-reverse to .media, or put the image last in the HTML.


Pattern 5: Input with a Button

Problem: a search box or newsletter form where the input fills the space and the button keeps its natural size.

<form class="search">
  <input type="search" placeholder="Search tutorials…">
  <button>Search</button>
</form>
.search {
  display: flex;
}

.search input {
  flex: 1;          /* fill all remaining width */
  min-width: 0;     /* inputs have a built-in minimum width; let it shrink */
}

.search button {
  flex: none;       /* keep the button's natural width */
}

Form controls like <input> have a default intrinsic width (roughly 20 characters), so without min-width: 0 the input can refuse to shrink on narrow phones and push the button out of the container.


Pattern 6: Wrapping Card Row (No Media Queries)

Problem: show cards in as many columns as fit: maybe 3 on a laptop, 2 on a tablet, 1 on a phone.

.cards {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.card {
  flex: 1 1 250px;  /* start at 250px, grow to fill the row, shrink if needed */
}

Let's work out what happens in an 800px container with 4 cards and a 16px gap:

How many 250px cards fit in one line?
  3 cards: 3 × 250 + 2 × 16 = 782px ≤ 800 ✓
  4 cards: 4 × 250 + 3 × 16 = 1048px > 800 ✗
→ Line 1 holds 3 cards, line 2 holds 1 card.

Line 1: free space = 800 − 782 = 18px, shared by 3 → each card = 256px
Line 2: one card alone, free = 800 − 250 = 550 → card = 800px (full width!)

We measured this in Chrome: the first three cards were 256px wide, and the fourth stretched across the whole 800px row.

That last-row stretching is the weakness of this pattern. Each flex line is sized independently, so Flexbox can't keep "columns" aligned between lines. If you need the last card to stay the same width as the others, that's a two-dimensional problem — use the grid version with repeat(auto-fill, minmax(250px, 1fr)) from Grid Layout Patterns. A Flexbox workaround is to drop the grow factor (flex: 0 1 250px), but then the row won't fill the full width.


Pattern 7: Equal-Height Cards with Aligned Buttons

Problem: cards in a row have different amounts of text, but their buttons should line up along the bottom.

We built this in the Flexbox chapter's complete example. The recipe in short:

.cards { display: flex; gap: 16px; }        /* stretch → equal heights */

.card {
  flex: 1;
  display: flex;
  flex-direction: column;                   /* card's content in a column */
}

.card .button { margin-top: auto; }         /* push button to the bottom */

Two flex containers cooperate: the outer row makes the cards equally tall (default align-items: stretch), and the inner column lets the auto margin push the button to the bottom of each card.


Pattern 8: Sidebar + Content

Problem: a fixed-width sidebar (filters, table of contents) and a main area that takes the rest.

.layout {
  display: flex;
  gap: 24px;
}

.sidebar {
  flex: 0 0 240px;   /* exactly 240px: no grow, no shrink */
}

.content {
  flex: 1;           /* everything else */
  min-width: 0;      /* so wide tables/code inside don't break the layout */
}

Making it wrap on small screens, without a media query

A clever variant lets the sidebar sit beside the content when there is room, and drop above it when there isn't:

.layout {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
}

.sidebar {
  flex: 1 1 240px;     /* ideal width 240px */
}

.content {
  flex: 999 1 0;       /* grabs almost all extra space */
  min-width: 60%;      /* when it can't be 60% wide, it wraps to a new line */
}

How it works: on a wide screen, both fit on one line; the content's huge grow factor (999 vs 1) means it takes almost all the free space, so the sidebar stays very close to 240px. When the container gets so narrow that 240px + gap + 60% no longer fit, the content wraps to the next line, and both then stretch to full width. In our test, at 900px wide the sidebar was about 241px next to the content, and at 400px the two were stacked, each 400px wide.

For layouts that need precise control on several breakpoints, you'll combine this with media queries from Responsive Design & Media Queries.


Pattern 9: The Holy Grail Layout

A classic exam and interview layout: header on top, footer at the bottom, and three columns in the middle — navigation, main content and an aside — where the main content is in the middle visually but first in the HTML (good for accessibility and SEO).

<body class="page">
  <header>Header</header>
  <div class="middle">
    <main>Main content (first in HTML)</main>
    <nav>Navigation</nav>
    <aside>Ads / related links</aside>
  </div>
  <footer>Footer</footer>
</body>
.page {
  display: flex;
  flex-direction: column;
  min-height: 100vh;      /* sticky footer (Pattern 3) */
  margin: 0;
}

.middle {
  flex: 1;                /* middle section fills the height */
  display: flex;          /* three columns */
}

main  { flex: 1; min-width: 0; }
nav   { flex: 0 0 180px; order: -1; }   /* visually on the left */
aside { flex: 0 0 180px; }
┌──────────────────────────────────────┐
│ Header                               │
├────────┬────────────────────┬────────┤
│ Nav    │ Main content       │ Aside  │
│ 180px  │ flex: 1            │ 180px  │
│        │                    │        │
├────────┴────────────────────┴────────┤
│ Footer                               │
└──────────────────────────────────────┘

order: -1 moves the nav before main visually. This is one of the few acceptable uses of order: the HTML order (main first) is the meaningful one, and the visual change doesn't confuse keyboard users much because the nav is a separate landmark. On phones, you would switch .middle to flex-direction: column in a media query.


Flexbox or Grid?

All these patterns could also be done with CSS Grid (coming up in CSS Grid). A simple rule of thumb:

Use Flexbox when…Use Grid when…
Items flow in one direction (a row or a column)You need rows and columns to line up together
The content should decide the sizes (content-out)The layout decides the sizes (layout-in)
Navbars, toolbars, buttons with icons, media objects, input groups, centeringPage layouts, card galleries with aligned columns, dashboards, forms with label columns
Wrapped items can have different widths per lineEvery cell should follow the same column tracks

In real projects you'll use both, often together: Grid for the page skeleton, Flexbox inside each component.


Pattern Cheat Sheet

PatternKey CSS
CenteringParent: display: flex; justify-content: center; align-items: center; min-height: …
Navbarjustify-content: space-between; align-items: center or margin-left: auto on the last item
Sticky footerBody: flex-direction: column; min-height: 100vh; main: flex: 1
Media objectImage: flex: none; body: flex: 1; min-width: 0; overflow-wrap: anywhere; container: align-items: flex-start
Input + buttonInput: flex: 1; min-width: 0; button: flex: none
Wrapping cardsflex-wrap: wrap; card: flex: 1 1 250px
Aligned card buttonsCard: display: flex; flex-direction: column; button: margin-top: auto
SidebarSidebar: flex: 0 0 240px; content: flex: 1; min-width: 0

Common Mistakes

  • Centering in a container with no extra height. Vertical centring needs free space; add min-height.

  • Avatars and icons getting squashed. Images in a flex row shrink by default; give them flex: none (or flex-shrink: 0).

  • Images stretched vertically. The default align-items: stretch stretches items without a fixed height; use align-items: flex-start or center.

  • Forgetting min-width: 0 on the flexible part, so long text, inputs or code blocks overflow.

  • Using margins on items for spacing and then fighting extra space at the ends. Use gap.

  • Expecting wrapped flex items to line up like a grid. Each line is sized separately; use Grid for that.

  • Using height: 100vh on the sticky-footer body. Long content then overflows the body; use min-height.


Interview / Exam Questions

1. How do you build a sticky footer with Flexbox?

Make the body (or a page wrapper) display: flex; flex-direction: column; min-height: 100vh; and give the main content flex: 1. The main area grows to fill leftover height, pushing the footer to the bottom of the screen on short pages; on long pages it simply follows the content.

2. In a navbar, how do you push only the last link to the right edge?

Make the navbar a flex container and give the last link margin-left: auto. In flex layout, an auto margin absorbs all available free space in that direction.

3. In a media object, why does the avatar get squashed when the text is long, and how do you fix it?

Flex items have flex-shrink: 1 by default, so when the content needs more room, the image shrinks too. Set flex: none (or flex-shrink: 0) on the image so it keeps its size, and min-width: 0 on the text part so the text wraps instead.

4. Cards have flex: 1 1 250px with gap: 16px in an 800px wrapping container. How wide is each of 4 cards?

Three cards need 3 × 250 + 2 × 16 = 782px, which fits; four would need 1048px. So line 1 has 3 cards sharing the 18px of free space (6px each) → 256px each; line 2 has the 4th card alone, which grows to the full 800px.

5. When would you choose Grid over Flexbox?

When the layout is two-dimensional — items need to line up in both rows and columns, like a gallery whose last row should keep the same column widths, or a full page layout with defined areas. Flexbox is best for one-dimensional rows or columns where content size drives the layout.

6. How do you place the main content in the middle column visually while keeping it first in the HTML?

In a flex row, give the navigation order: -1 (or give main order: 1 and aside order: 2). order changes only the visual order; the HTML order, which screen readers and the keyboard use, still has main first.


Summary

  • Most real-world flex layouts are a handful of patterns: centering, navbar, sticky footer, media object, input group, wrapping cards, aligned card buttons, sidebar and the holy grail.

  • The same few tools appear again and again: flex: 1 for "take the rest", flex: none for "keep my size", margin: auto for "push", min-width: 0 for "allow shrinking", gap for spacing.

  • Nesting flex containers is normal and expected.

  • Flexbox sizes each line separately; when columns must line up across rows, switch to Grid.

Next, we move to the second big layout system, built for two dimensions: CSS Grid.