Log inSign up free
Mastering Modern CSS: From Zero to Pro
  1. Getting started

    1. CSS Lesson 1: What Is CSS?
    2. CSS Lesson 2: Selectors and Rules
    3. CSS Lesson 3: How CSS Works: The Cascade
    4. CSS Lesson 4: Colour and Backgrounds
    5. CSS Lesson 5: Typography and Text
    6. CSS Lesson 6: The Box Model
    7. CSS Lesson 7: Units and Sizing
    8. CSS Lesson 8: Display and Positioning
    9. CSS Lesson 9: Flexbox
    10. CSS Lesson 10: Grid
    11. CSS Lesson 11: Responsive Design
    12. CSS Lesson 12: Final Project
Mastering Modern CSS: From Zero to Pro

Getting started · Lesson 9 of 12 · 7 min read · By Jack

CSS Lesson 9: Flexbox

Focus: Arranging items in a row or column, controlling alignment and spacing, and building layouts that adapt to the space available.

Downloads for this lesson

Sign up free (or log in) to download these files.

Focus: Arranging items in a row or column, controlling alignment and spacing, and building layouts that adapt to the space available.

Downloads are at the top of this lesson:

  • css_lesson9_flex_container_properties.csv lists the container properties.
  • css_lesson9_flex_item_properties.csv lists the item properties.

What you'll learn

By the end, you'll be able to turn any parent into a flex container and arrange its children in rows or columns. You'll also be able to align and space items using the main and cross axes, and let cards grow, shrink and wrap.

1. Why Flexbox?

Until now, elements have mostly stacked down the page (normal flow). Flexbox lets you lay items out in one dimension, either a row or a column. It is ideal for navigation bars, button groups, card rows, toolbars and centring content.

<nav class="nav">  
  <a href="#">Home</a>  
  <a href="#">Lessons</a>  
  <a href="#">About</a>  
</nav>
.nav {  
  display: flex;  
}

That one declaration puts the links side by side. The parent is the flex container. Its direct children are flex items.

Only direct children become flex items. A grandchild is not affected by the container's flex rules.

2. The two axes

Flexbox is built on two axes:

AxisMeaning
Main axisThe direction items are laid out. A row by default.
Cross axisThe axis perpendicular to the main axis.

Change the direction and the axes swap:

.stack {  
  display: flex;  
  flex-direction: column;  
}

Now the main axis is vertical and the cross axis is horizontal.

The values are row (default), row-reverse, column and column-reverse.

Quick check 1: With flex-direction: column, which direction is the main axis?

3. Spacing with gap

Use gap to put space between items without adding margins to each one.

.nav {  
  display: flex;  
  gap: 1rem;  
}

You can use any length unit. gap only adds space between items, not around the outside edges.

4. justify-content: distribute along the main axis

.toolbar {  
  display: flex;  
  justify-content: space-between;  
}
ValueResult
flex-startItems packed at the start
centerItems centred
flex-endItems packed at the end
space-betweenFirst and last items at the edges, equal space between
space-aroundEqual space around each item
space-evenlyEqual space between items and edges

A classic header has the brand on the left and links on the right:

<header class="header">  
  <strong class="brand">CSS Course</strong>  
  <nav>Links here</nav>  
</header>
.header {  
  display: flex;  
  justify-content: space-between;  
  align-items: center;  
  padding: 1rem;  
}

5. align-items: align along the cross axis

.row {  
  display: flex;  
  align-items: center;  
}
ValueResult
stretchItems stretch to fill the cross axis (default)
flex-startItems align at the cross-axis start
centerItems are centred on the cross axis
flex-endItems align at the cross-axis end
baselineItems align by their text baselines

Remember: justify-content works on the main axis. align-items works on the cross axis. If you change flex-direction to column, they swap directions.

Quick check 2: In a default row, which property would you use to centre items vertically?

6. Centring anything

Flexbox makes the classic "centre it both ways" task short:

<section class="hero">  
  <h1>Welcome</h1>  
</section>
.hero {  
  display: flex;  
  justify-content: center;  
  align-items: center;  
  min-height: 60vh;  
}

The container needs extra height, such as min-height, for vertical centring to be visible. If it is only as tall as its content, there is no spare space to centre within.

7. Wrapping with flex-wrap

By default, flex items try to stay on one line and may shrink or overflow. Allow wrapping like this:

.cards {  
  display: flex;  
  flex-wrap: wrap;  
  gap: 1rem;  
}

When the row runs out of room, items move onto a new line.

8. Sizing items: flex-grow, flex-shrink, flex-basis

These item properties control how items share space:

PropertyDefaultMeaning
flex-grow0How much an item may grow to take extra space
flex-shrink1How readily it shrinks when space is short
flex-basisautoIts starting size before growing or shrinking

They combine in the flex shorthand: flex: grow shrink basis.

.card {  
  flex: 1;  
}

flex: 1 lets each card grow and shrink to share space, which makes equal-width cards.

Useful shorthands:

ShorthandMeaning
flex: 1Share available space
flex: 0 0 200pxStay at 200px; do not grow or shrink
flex: autoGrow and shrink from the item's own size
flex: noneDo not grow or shrink

9. A responsive card row

Combine wrapping with a flexible basis:

<div class="cards">  
  <article class="card">One</article>  
  <article class="card">Two</article>  
  <article class="card">Three</article>  
</div>
.cards {  
  display: flex;  
  flex-wrap: wrap;  
  gap: 1rem;  
}  
  
.card {  
  flex: 1 1 16rem;  
  padding: 1rem;  
  border: 1px solid #cbd5e1;  
  border-radius: 0.75rem;  
}

Each card starts at 16rem, may grow to fill spare space, and wraps onto another line when there isn't room. Resize your browser to watch it adapt.

10. Controlling one item

  • align-self overrides align-items for a single item.
  • margin-left: auto pushes an item (and those after it) to the far end.
  • order changes visual order, but screen readers and keyboard users follow the source order, so prefer reordering your HTML where possible.
.toolbar {  
  display: flex;  
  gap: 0.75rem;  
}  
  
.toolbar .logout {  
  margin-left: auto;  
}

Common mistakes

SymptomWhat to check
Flex properties do nothingThe parent needs display: flex, and you must style direct children
Items overflow the containerAdd flex-wrap: wrap, or reduce fixed widths
Long text overflows a flex itemTry min-width: 0 on the item
Vertical centring failsGive the container extra height, e.g. min-height
Properties act the "wrong" wayCheck flex-direction, since the axes swap in a column
Tab order feels oddAvoid relying on order; reorder the HTML instead

Exercises

Try these before opening the answer key.

1. Write the CSS to turn .menu into a horizontal row with 1.5rem between items.

2. Which property distributes items along the main axis, and which aligns them on the cross axis?

3. Write the CSS to centre .box horizontally and vertically inside .stage, which should be at least 50vh tall.

4. Three cards should share a row equally. What flex value goes on each card?

5. Cards must wrap onto new lines when space runs out, with each starting at 15rem. Write the container and card rules.

6. In a toolbar, one "Log out" button should sit at the far right. How can you do it without changing the HTML?

7. Why might align-items: center appear to do nothing on a short container?

8. Build it. Create a page header with a brand on the left and three links on the right, vertically centred. Then add a row of three equal-width cards below it. Resize the window and check that nothing overflows.

9. Experiment. Switch .cards to flex-direction: column. Which properties now act on which axis? Then switch back and try each justify-content value.

Free resources

  • MDN Web Docs: the Basic concepts of flexbox and Aligning items in a flex container guides.
  • Flexbox Froggy (a free game): practise justify-content, align-items and flex-direction.
  • Browser DevTools: the flex badge and overlay in the Elements panel visualise axes, gaps and item sizes.

Key takeaways

  • display: flex on the parent makes its direct children flex items.
  • The main axis follows flex-direction; the cross axis is perpendicular to it.
  • justify-content handles the main axis and align-items handles the cross axis.
  • Use gap for spacing, flex-wrap for adaptability and flex to size items.
  • Flexbox is for one-dimensional layout. Lesson 10 covers Grid for two dimensions.

Quick check 1: Vertical.

Quick check 2: align-items: center (the cross axis is vertical in a row).

Exercise 1:

.menu {  
  display: flex;  
  gap: 1.5rem;  
}

Exercise 2: justify-content for the main axis; align-items for the cross axis.

Exercise 3:

.stage {  
  display: flex;  
  justify-content: center;  
  align-items: center;  
  min-height: 50vh;  
}

Exercise 4: flex: 1.

Exercise 5:

.cards {  
  display: flex;  
  flex-wrap: wrap;  
  gap: 1rem;  
}  
  
.card {  
  flex: 1 1 15rem;  
}

Exercise 6:

.logout {  
  margin-left: auto;  
}

Keep track of your learning

This lesson comes with 2 downloads. Create a free account to unlock them and track your progress.

  • Track your progress through every course
  • Take the quizzes and see your score
  • Download the worksheets and resources
  • Get a certificate when you finish

Related reading on our blog

Rather have it done for you?

We build websites for small businesses

Everything in this course is what we do every day for local businesses: fast, mobile-friendly sites that are built to be found on Google. See our web design services or our website packages.