CodeBlanks Logo Icon CodeBlanks

Responsive flex layout

CSS course · Intermediate · Lesson 54/98

Build a responsive flex layout with flex-wrap.

Flexible wrapping with flex-wrap

A flex container lines up all items in a single row by default. When the screen narrows, items overflow or get squeezed. flex-wrap: wrap lets items drop to the next line when they don't fit, so the flex layout becomes responsive too.

It's the most practical fix for tags, button groups and card rows: however many items there are, they adapt to the screen width.

Base width with flex-basis

Combining flex-wrap: wrap with flex-basis sets each item's base width. flex: 1 1 200px says the item starts at 200 pixels and can stretch; items that don't fit drop to the next line.

This triple (grow, shrink, basis) is flexible: one column on narrow screens, side by side on wide ones, with no extra media query.

Row spacing with gap

When you use flex-wrap: wrap, the gap declaration sets both horizontal and vertical spacing. A single value applies the same spacing in both directions; two values set row then column spacing.

This keeps wrapped items evenly spaced and avoids the mess of margins.

Exercise Make the tag row responsive

Make the .tags container a flex layout; let items wrap when they don't fit and leave 0.5rem of spacing between rows. Write the display, flex-wrap and gap declarations.

Show example solution
.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

Test yourself

  1. What does flex-wrap: wrap do?

    .tags {
      display: flex;
      flex-wrap: wrap;
    }
    • Items drop to the next line when they don't fit
    • Forces items into a single row
    • Hides all items
    • Adds a horizontal scrollbar
    Show answer

    Items drop to the next line when they don't fit — Correct. wrap moves overflowing items to the next line; the layout stays intact.

  2. Write the wrap value

    .tags {
      display: flex;
      flex-wrap: ____;
      gap: 0.5rem;
    }
    Show answer
    .tags {
      display: flex;
      flex-wrap: wrap;
      gap: 0.5rem;
    }
  3. Match each flex value to its meaning

    flex-wrap: nowrap
    Force a single row
    flex-wrap: wrap
    Drop overflow to next line
    flex-wrap: wrap-reverse
    Wrap in reverse order
    flex: 1 1 200px
    Start at 200px, stretch

All lessons in Intermediate