Chapter 7 of 15

CSS Flexbox Tutorial for Beginners (with Pictures)

Flexbox is the tool you will use almost every day. It puts boxes side by side, spaces them nicely, and centers things with two lines of code. We will go slowly, one picture at a time.

The problem flexbox solves

In the box model chapter you saw that block boxes like <div> always stack on top of each other. That is fine for text. But real websites need things side by side: a logo and a menu, three product cards, a photo next to some text.

Years ago, developers used tricks to do this, and the tricks broke easily. Flexbox was made to solve this problem properly. Today every modern browser supports it, so you can use it without fear.

HTML
<div class="row">
  <div>1</div>
  <div>2</div>
  <div>3</div>
</div>
Result in the browser
1
2
3

Without flexbox: three boxes, one under the other. Let us fix that.

Two parts: the container and the items

Flexbox always has two parts. You need to know these two words:

  • Flex container: the parent element. You give it display: flex.
  • Flex items: the direct children of that parent. They follow the container's rules.
A dashed parent box holding three blue child boxes
The parent gets display: flex. Its direct children become flex items.
CSS
.row {
  display: flex;
}
Result in the browser
1
2
3

One line of CSS, and the boxes are in a row.

Only direct childrenFlexbox affects the children, not the grandchildren. If an item has its own boxes inside, those boxes are not flex items, unless you give that item display: flex too.

Two directions: main axis and cross axis

Flexbox does not think "left/right" and "up/down". It thinks in two axes (an axis is just a line with a direction):

Main axis arrow along the row and cross axis arrow going down
Flexbox thinks in two directions. Main axis = the way items line up. Cross axis = the other way.
  • The main axis is the direction the items line up. For a row, it goes left to right.
  • The cross axis goes across it. For a row, it goes top to bottom.

There is a different property for each axis:

PropertyWorks onIn a normal row
justify-contentMain axisLeft ↔ right
align-itemsCross axisUp ↕ down

justify-content: spread items along the row

justify-content decides what to do with the empty space on the main axis. Here are all the values in one picture:

Six rows showing flex-start, center, flex-end, space-between, space-around and space-evenly
justify-content moves items along the main axis.
CSS
.row {
  display: flex;
  justify-content: space-between;
}
Result in the browser
1
2
3

You will use space-between (logo left, menu right) and center the most.

Try it yourselfCopy the code into your own file. Change space-between to center, then flex-end. Save and reload after each change.

align-items: line up items up and down

align-items does the same job on the cross axis. You only see a difference when the container is taller than the items, or when the items have different heights.

Four boxes showing items aligned to top, center, bottom and stretched
align-items moves items along the cross axis (up and down in a row). stretch is the default.
CSS
.row {
  display: flex;
  align-items: center;
  height: 140px;
}
Result in the browser
1
2
is
tall
3

Notice the default is stretch. That is why, in a flex row, all boxes become the same height. Many beginners get confused by this, so keep it in mind.

The famous perfect center

Centering a box used to be hard in CSS. With flexbox it takes three lines:

CSS
.hero {
  display: flex;
  justify-content: center;  /* center on main axis */
  align-items: center;      /* center on cross axis */
  height: 200px;
}
Result in the browser
I am in the middle

flex-direction: rows or columns

By default items go in a row. Change flex-direction to column and they go top to bottom. Look at the arrow in the picture. The main axis turns:

Row layout with a sideways arrow and column layout with a downward arrow
With column the main axis turns down. Now justify-content works up and down, and align-items works left and right.
CSS
.stack {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
Result in the browser
1
2
3
The most common confusionIn a column, justify-content moves things up and down, and align-items moves them left and right. They swap because the axes turned. If something is not moving the way you expect, check the direction first.

gap: easy space between items

Want space between the items but not on the outside edges? Use gap. It is much easier than adding margins to every item.

CSS
.row {
  display: flex;
  gap: 20px;
}
Result in the browser
1
2
3

flex-wrap: when items don't fit

By default flexbox keeps every item on one line, even if it has to squeeze them very thin. On a phone, this looks bad. flex-wrap: wrap lets items move to the next line:

Left: six squeezed items in one line. Right: four items on the first line, two on the second
Without wrap, flexbox squeezes everything into one line. With wrap, items move to the next line.
CSS
.gallery {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
.gallery > div {
  width: 150px;
}
Result in the browser
1
2
3
4
5
6
7

Make your browser window narrow and wide. The items move to new lines by themselves.

flex: let items grow

Sometimes you want one item to fill all the empty space, like a search box in a toolbar. The flex property does this:

Three rows showing free space, one item growing, and two items growing in a one to two ratio
flex: 1 means "take a share of the free space". flex: 2 takes two shares.
CSS
.search { flex: 1; }   /* takes all free space */
.main   { flex: 2; }   /* takes 2 shares */
.side   { flex: 1; }   /* takes 1 share */
Result in the browser
1
2 (flex: 1)
3

The free space is shared out. An item with flex: 2 gets twice as much extra space as an item with flex: 1. Items without flex get no extra space.

For cards that wrapflex: 1 1 200px means: grow, shrink if needed, and start at 200px wide. Use it with flex-wrap: wrap to make a card row that shows 3 cards on a laptop and 1 on a phone.

A small trick: margin auto

In a flex row, margin-left: auto on one item pushes it, and everything after it, to the far right.

Logo on the left, three links pushed to the right by an auto margin
An auto margin pushes items away. Very handy for menus.
CSS
.about {
  margin-left: auto;
}
Result in the browser
Logo
About
Blog
Login

align-self: one item breaks the rule

align-items works on all items. If you want just one item to be different, give that item align-self:

CSS
.row  { display: flex; align-items: flex-start; height: 120px; }
.last { align-self: flex-end; }
Result in the browser
1
2
3

Common mistakes (and quick fixes)

ProblemFix
Nothing happensDid you put display: flex on the parent, not on the items?
align-items: center does nothingThe container has no extra height. Give it a height or min-height.
Items move the wrong wayCheck flex-direction. In a column the axes swap.
Items are squeezed on phonesAdd flex-wrap: wrap.
Images stretch strangelyAdd align-items: flex-start or center to stop the default stretch.

Cheat sheet

Put on the containerWhat it does
display: flexTurn on flexbox
flex-directionrow or column
justify-contentSpace on the main axis
align-itemsLine up on the cross axis
gapSpace between items
flex-wrapAllow new lines
Put on an itemWhat it does
flex: 1Grow to fill free space
align-selfDifferent alignment for this one item
margin-left: autoPush this item (and the rest) to the right

Practice time

  1. Build the navbar from this chapter, then add a fourth link.
  2. Make a full-screen box (height: 100vh) and put a heading in the exact center.
  3. Make a row of 6 cards with flex-wrap. Check it on the phone view in your browser.
  4. Make a toolbar: a logo, a search box with flex: 1, and a button.

Quick summary

  • Flexbox = a container (parent) and items (children).
  • justify-content works on the main axis, align-items on the cross axis.
  • flex-direction: column turns the main axis, so the two properties swap.
  • gap for space, flex-wrap for small screens, flex: 1 to grow.
  • Real layouts are flex boxes inside flex boxes.