Thuta Learning
CSS
AdvancedWeb DevelopmentBeginner

Flex Container

CSSLesson 1830 min

What you'll walk away with

  • Control item order and line breaking with the four flex-direction values (including reverse) and flex-wrap
  • Work out in pixels how space-between, space-around and space-evenly differ
  • Tell align-items (inside one line) apart from align-content (between several lines)
  • Space items with gap instead of item margins

Explain it simply

Explain it simply

Think of a flex container as a bus. The container properties are the driver's rules: which way the rows face (flex-direction), whether passengers may continue in the next row when one is full (flex-wrap), how people spread out within a row (justify-content), how each one sits in their seat (align-items), and how much room is left between them (gap).

The key point is that all of these rules live in one place, on the parent. You never chase each child individually; change the container and every item follows.

Problem → Why → Solution

The problem: margin spacing falls apart when items wrap

To space the buttons in a toolbar, every item gets margin-right: 12px. When the screen narrows and flex-wrap: wrap breaks them onto two lines, three problems appear: each line ends with a useless 12px after its last button, so the right edge no longer lines up; the two lines touch with no space between them; and once the toolbar is given a height, the lines spread far apart across the whole container.

toolbar.css
.toolbar {
  display: flex;
  flex-wrap: wrap;
  height: 200px;           /* lines drift apart */
}
.toolbar > * {
  margin-right: 12px;      /* trailing space on every line */
}                          /* and no space between lines */

Why does this happen?

A margin belongs to each item, and the item does not know it is the last one on a line, so it keeps the margin anyway. gap belongs to the container and is inserted only between items, so nothing is left at the start or end of a line, and row-gap also separates the lines. The drifting lines come from align-content's default, stretch, which shares the container's extra height among the lines; align-content: flex-start packs them at the top.

Core concept: grouping the container properties by axis

The container properties are easiest to remember in four groups. First, direction: flex-direction is row, row-reverse, column or column-reverse. The reverse values display items backwards but leave the HTML order alone, so the Tab key still follows the original order. Second, line breaking: flex-wrap defaults to nowrap, so items shrink to squeeze onto one line, and only wrap lets them move to a new line. flex-flow: row wrap is the shorthand that sets both properties at once.

Third, sharing free space on the main axis: that is justify-content. With three 50px items in a 400px row there are 250px of free space, and each value splits those 250px as the table below shows. In a column the same values work top to bottom, but only if the container has a height that leaves free space to share.

ValueLeft edge of each item (px)
flex-start (default)0, 50, 100: all packed at the start
center125, 175, 225
space-between0, 175, 350: no space at the edges
space-around41.7, 175, 308.3: half-size edge space
space-evenly62.5, 175, 287.5: every gap equal

Fourth, alignment on the cross axis: align-items aligns each item within its line (stretch by default, or flex-start, flex-end, center, baseline). baseline lines up the bottom of the text in items with different font sizes. align-content, by contrast, aligns the lines as a group in a wrapping container with several lines, and has no effect at all in a nowrap container. Finally, gap, the shorthand for row-gap and column-gap, adds space only between items and between lines. Gap space is subtracted before free space is calculated, so justify-content shares whatever remains after the gaps.

Reading a container in order
  1. Direction: axis and order
  2. Wrap: one line or many?
  3. justify-content: free space in a line
  4. align-items / align-content: cross
  5. gap: space between items and lines

align-items moves items inside a line; align-content moves the lines themselves.

General pattern

css
container {
  display: flex;
  flex-direction: row | row-reverse | column | column-reverse;
  flex-wrap: nowrap | wrap;
  justify-content: flex-start | center | space-between | ...;
  align-items: stretch | flex-start | center | baseline | ...;
  align-content: normal | flex-start | center | ...;  /* wrap only */
  gap: row-gap column-gap;
}

Every one of these goes on the parent. align-content only matters in a wrapping container, and gap with a single value spaces rows and columns equally.

Example: a wrapping row of feature cards

This example combines four container properties into a card row that breaks into lines depending on the screen width. The flex shorthand on .feature-card is covered in the next lesson; for now read it as "start at 240px, then grow or shrink as needed".

.features {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  justify-content: center;
  align-items: stretch;
}

.feature-card {
  flex: 1 1 240px;
}

Code breakdown

  1. Line 3flex-wrap: wrap;

    Lets a card move to a new line once its 240px no longer fits. Without it, all three cards would shrink and stay on a single line.

  2. Line 4gap: 20px;

    Adds 20px between cards and 20px between wrapped lines in one go, with nothing left over at the line edges.

  3. Line 5justify-content: center;

    Because the cards grow to fill each line, no free space remains, so this line has no visible effect here. Switch the cards to flex: 0 1 240px, without growing, and every line would gather in the centre.

  4. Line 6align-items: stretch;

    Spells out the default: every card in a line becomes as tall as the tallest card in that line.

  5. Line 10flex: 1 1 240px;

    Each card starts at 240px and shares whatever room is left on its line. 240px is not a minimum width: in a container narrower than 240px the card keeps shrinking.

You should see
In an 800px container all three cards share one line at about 253px each. At 500px, two 240px cards fill the first line and the third wraps and stretches to the full 500px. In a 200px container a card shrinks to 200px. Cards on the same line are always equal in height.

Seeing align-items and align-content side by side

text
flex-wrap: wrap, container 200px tall, two lines
------------------------------------------------
align-content: normal (stretch)      align-content: flex-start
+----------------------------+       +----------------------------+
| [a] [b] [c] [d]            |       | [a] [b] [c] [d]            |
|                            |       | [e]                        |
|  line 1 gets half the      |       |                            |
|  extra height              |       |  lines packed at the top,  |
| [e]                        |       |  free space stays below    |
|                            |       |                            |
+----------------------------+       +----------------------------+

On the left, two lines of 20px-tall items share the 200px container at 100px each, so the second line starts halfway down. align-items can only align items inside each line, so it cannot close that gap; only align-content moves the lines. Try center, space-between or flex-end on the right-hand box and watch the two lines travel together as one block.

In real projects

Where this shows up in real projects

Site headers most often pair justify-content: space-between with align-items: center, sending the logo to the left edge and the menu to the right edge while lining up their different heights on one centre line. Tag lists, filter chips and the size buttons of an online shop use flex-wrap: wrap with something like gap: 8px, so they break into lines automatically at any width.

A form's action bar uses justify-content: flex-end to push "Cancel" and "Save" to the right. A pricing table uses align-items: baseline so a big price and a small "/month" share the same text baseline. Chat apps sometimes use flex-direction: column-reverse to show the newest messages at the bottom, but check that the reading order for screen readers, which follows the HTML, still makes sense.

Common mistakes

Common mistakes

1. Trying align-content on a nowrap container

align-content: center on a container without flex-wrap does nothing, and that is not a browser bug. To align items in a single line, use align-items; to align lines, add flex-wrap: wrap first.

2. Spacing items with margins

Spacing with margin-right forces hacks such as :last-child { margin-right: 0 }, and even that fails once items wrap. Put gap on the container; every modern browser supports gap in flexbox.

3. Using a reverse direction to fix the order

row-reverse changes only the visual order; Tab order and screen-reader order still follow the HTML. When the meaningful order should change, change the HTML. Keyboard users otherwise see focus jump backwards across the screen, which is confusing and fails accessibility audits.

Best practices

Best practices

  • Add flex-wrap: wrap up front to any list whose item count can change (tags, chips, buttons), so longer translations do not overflow.
  • Whenever you give a wrapping container a height, set align-content at the same time.
  • Avoid space-between on wrapping lists of more than two items: a short last line gets flung to the far edges.

Mini challenge

Mini challenge: a header and a tag box

Using container properties only, with no styles on the items, build a header and a wrapping tag box.

  • .header puts the logo at the left edge and .menu at the right edge, centred on the cross axis
  • Links inside .menu are 16px apart (no margins)
  • Tags in .tags (240px by 160px) wrap, with 12px between tags and 8px between lines
  • The tag lines stay packed at the top of the box instead of spreading out
container.html
<style>
  /* TODO: .header = logo left edge, menu right edge, centred on the cross axis */
  /* TODO: .menu = links 16px apart, no margins */
  /* TODO: .tags = 240px x 160px, wrapping, 12px between tags, 8px between lines,
     lines packed at the top */
  .tags span { padding: 4px 8px; background: #e2e8f0; }
</style>

<header class="header">
  <strong style="font-size: 28px">Shop</strong>
  <nav class="menu"><a href="#">Deals</a><a href="#">Cart</a></nav>
</header>
<div class="tags">
  <span>css</span><span>flexbox</span><span>layout</span><span>gap</span>
  <span>wrap</span><span>align</span><span>responsive</span>
</div>

Expected: "Shop" sits at the left edge and Deals and Cart at the right edge, on the same centre line. The tags break into two lines inside the 240px box, only 8px apart, packed at the top with empty space left below.

Show hint

With two values, gap is row-gap (between lines) then column-gap (between items). Use align-content to pack the lines at the top.

Show solution
container.html
<style>
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .menu {
    display: flex;
    gap: 16px;
  }
  .tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px 12px;
    align-content: flex-start;
    width: 240px;
    height: 160px;
    border: 1px solid #cbd5e1;
  }
  .tags span { padding: 4px 8px; background: #e2e8f0; }
</style>

<header class="header">
  <strong style="font-size: 28px">Shop</strong>
  <nav class="menu"><a href="#">Deals</a><a href="#">Cart</a></nav>
</header>
<div class="tags">
  <span>css</span><span>flexbox</span><span>layout</span><span>gap</span>
  <span>wrap</span><span>align</span><span>responsive</span>
</div>

Quick quiz 1 / 3

Two 100px items sit in a 400px row with justify-content: space-evenly. Where is the first item's left edge?

Quick quiz 2 / 3

A 300px-tall container without flex-wrap gets align-content: center. What happens?

Quick quiz 3 / 3

In a wrapping toolbar you want 10px between lines and 20px between items. Which declaration is right?

What to remember

  • flex-direction picks the axis and the visual order; the reverse values leave HTML and Tab order untouched.
  • justify-content shares free space on the main axis, so it has no visible effect when items grow to fill it.
  • align-items aligns items within a line; align-content aligns the lines of a wrapping container.
  • Use gap on the container instead of margins on the items.

Basic concepts of Flexbox — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Flex Container | Thuta Learning