Thuta Learning
CSS
AdvancedWeb DevelopmentBeginner

Flexbox Intro

CSSLesson 1725 min

What you'll walk away with

  • Explain that flex-direction sets the main axis and the cross axis runs perpendicular to it
  • Predict correctly, even after changing direction, that justify-content works on the main axis and align-items on the cross axis
  • Know which default behaviours change for children the moment a parent becomes a flex container
  • Tell one-dimensional (flex) layouts from two-dimensional (grid) ones and choose accordingly

Explain it simply

Explain it simply

Picture Flexbox as beads on a string. The string (the main axis) can run horizontally or vertically. The beads (the flex items) line up in order along it, and you control two things separately: how they spread along the string (packed at the start, centred, evenly spaced) and how they line up across it.

That is why flexbox shows up in navigation bars, button groups, rows of an icon plus text, and every "I just want this box centred" problem: all of them are things on a single string.

Problem → Why → Solution

The problem: switching to a column breaks the centring

You memorised "justify-content is horizontal, align-items is vertical". To put a card's button at the bottom, you switch to flex-direction: column and add align-items: flex-end. The button does not move down; it jumps to the right. And text you centred with justify-content is no longer centred left to right but top to bottom.

.card {
  display: flex;
  flex-direction: column;
  justify-content: center;  /* "horizontal"? now vertical */
  align-items: flex-end;    /* "vertical"? now pushes right */
  height: 240px;
}

Why does this happen?

justify-content and align-items know nothing about left, right, up or down; they only know axes. justify-content always works on the main axis and align-items always on the cross axis. flex-direction: column turns the main axis vertical, so the visible direction of both properties turns with it. Think in axes and this "bug" becomes predictable behaviour.

Core concept: the main axis and the cross axis

As soon as an element gets display: flex, it becomes a flex container and each of its direct children becomes a flex item; grandchildren are not affected. Loose text written directly inside the container is wrapped by the browser in an invisible, anonymous flex item.

Flexbox is a one-dimensional layout: it places items along a single axis, the main axis. flex-direction picks it: row (the default) follows the reading direction, left to right in English and right to left under dir="rtl", while column runs top to bottom. The cross axis is always perpendicular to the main axis.

Tie each container property to an axis: justify-content distributes free space along the main axis, and align-items positions items on the cross axis. Changing the direction never changes which property owns which axis; only the axis turns.

text
flex-direction: row vs column
-----------------------------
row (default)                       column
main axis ---------------->         +---------+   main axis
+-------+-------+-------+  cross    | item 1  |      |
| item1 | item2 | item3 |  axis     +---------+      |
+-------+-------+-------+   |       | item 2  |      v
                            v       +---------+
                                    cross axis ---->

Keep the term free space in mind as well. On the main axis, the container's size minus the sizes of all the items is the free space, and justify-content only distributes that leftover room. If the items grow to take everything (covered in the Flex Items lesson), no free space remains and justify-content has no visible effect. When the container itself should sit inside a line of text, use display: inline-flex; the axis rules inside are identical.

Flex items also get new defaults. align-items defaults to stretch, so items without a height fill the full height of the row. Items shrink when space runs out but do not grow to fill spare space on their own. They stay on one line instead of wrapping, ignore float and vertical-align, and their margins no longer collapse.

Read a flex layout by its axes
  1. Find the main axis from flex-direction
  2. Cross axis = the perpendicular one
  3. justify-content acts on the main axis
  4. align-items acts on the cross axis

Drop the words horizontal and vertical; think only main and cross.

General pattern

css
container {
  display: flex;                 /* children become flex items */
  flex-direction: row | column;  /* picks the main axis */
  justify-content: value;        /* along the main axis */
  align-items: value;            /* across, on the cross axis */
}

display: flex creates the container and flex-direction picks the main axis. The other two properties each own one axis. The full list of values comes in the next lesson, Flex Container.

Example: centring a box in both directions

Flexbox's most famous use is putting one child dead centre in its container. Comments often label these two properties "horizontal" and "vertical", which is only true for a row, so here they name the axes instead. Assume the container holds a single 100 by 50 child.

.center-box {
  display: flex;
  justify-content: center; /* main axis (a row by default) */
  align-items: center;     /* cross axis (perpendicular) */
  min-height: 300px;
}

Code breakdown

  1. Line 2display: flex;

    Makes .center-box a flex container and its child a flex item. No flex-direction is given, so the main axis is a row, left to right.

  2. Line 3justify-content: center; /* main axis (a row by default) */

    Splits the free space on the main axis equally before and after the item, so it lands in the middle from left to right.

  3. Line 4align-items: center; /* cross axis (perpendicular) */

    Centres the item on the cross axis, top to bottom here. Without this line, the default stretch would make a child with no height fill the container's full height.

  4. Line 5min-height: 300px;

    Gives the cross axis room to centre in by making the container at least 300px tall, while still letting it grow if the content gets longer.

You should see
The child sits dead centre in the box. For example, a 100 by 50 child in a 600 by 300 box lands 250px from the left and 125px from the top.

Flex or grid?

Flex thinks content-first: it looks at how big the items are and spreads them along one line. Grid thinks layout-first: it draws rows and columns, then drops items into the cells. When items must line up both across and down, reach for grid.

LayoutBetter tool
Navbar, toolbar, button groupFlex
Avatar plus text (media object)Flex
Header, sidebar, main and footer frameGrid
Card gallery whose columns must alignGrid

In real projects

Where this shows up in real projects

Almost every site header is a flex row: logo on the left, menu on the right, with align-items: center lining up a tall logo and short links on one centre line. Each message in a chat app is a media object, an avatar beside text, which is another flex row. Putting a label, an input and a button on one line in a form is the same pattern.

Column direction is just as common: a sidebar that stacks links top to bottom and sends "Log out" to the bottom, or a card that stacks an image, text and a button with the button pinned to the bottom. Turning a row into a column on mobile takes a single flex-direction change inside a media query, which makes flex convenient for responsive design. In right-to-left languages such as Arabic or Hebrew, a row automatically runs right to left, another strength of thinking in axes.

Common mistakes

Common mistakes

1. Switching to column without swapping the properties

If justify-content did your left-right centring in a row, align-items has to do that job in a column. Whenever the direction changes, re-check both properties against the axes.

2. Centring a column in a container with no height

With flex-direction: column; justify-content: center; but an auto height, the container is exactly as tall as its content, so there is no free space to distribute and nothing moves. Give it a height or a min-height.

3. Expecting grandchildren to become flex items

Give <nav> display: flex while the links live inside <ul><li>, and the only flex item is the <ul>. To line up the links, put display: flex on the <ul>.

Best practices

Best practices

  • When debugging, click the flex badge in DevTools to turn on the overlay, which shows the main axis and the free space.
  • Write "main axis / cross axis" in CSS comments instead of "horizontal / vertical" so the comments stay true when the direction changes.
  • If a row should read in a different visual order, fixing the HTML order is kindest to keyboard users.

Mini challenge

Mini challenge: a media object and a sidebar

Build two small layouts, one on a row axis and one on a column axis.

  • .media places the avatar beside the text, centred on the cross axis, 12px apart
  • The children of .sidebar (300px tall) stack from top to bottom
  • The .logout link sits at the bottom of the sidebar, without margin hacks
  • Sidebar children stay full sidebar width (keep the default stretch)
axes.html
<style>
  /* TODO: .media = avatar beside text, centred on the cross axis, 12px gap */
  .avatar { width: 48px; height: 48px; border-radius: 50%; background: #94a3b8; }
  /* TODO: .sidebar = 200px wide, 300px tall, children top to bottom,
     with .logout pushed to the bottom */
</style>

<div class="media"><div class="avatar"></div><p>Mya Mya posted a new photo</p></div>
<nav class="sidebar">
  <div class="links"><a href="#">Home</a> <a href="#">Inbox</a></div>
  <a class="logout" href="#">Log out</a>
</nav>

Expected: The text sits to the right of the avatar on the same centre line. In the sidebar, Home and Inbox are at the top and "Log out" is at the bottom, both spanning the sidebar's full width.

Show hint

The sidebar's main axis is a column, so justify-content (space-between) is the property that pushes its two children to the start and the end.

Show solution
axes.html
<style>
  .media {
    display: flex;
    align-items: center;
    gap: 12px;
  }
  .avatar { width: 48px; height: 48px; border-radius: 50%; background: #94a3b8; }
  .sidebar {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    width: 200px;
    height: 300px;
    background: #f1f5f9;
  }
</style>

<div class="media"><div class="avatar"></div><p>Mya Mya posted a new photo</p></div>
<nav class="sidebar">
  <div class="links"><a href="#">Home</a> <a href="#">Inbox</a></div>
  <a class="logout" href="#">Log out</a>
</nav>

Quick quiz 1 / 3

In a container with flex-direction: column, which declaration centres the items from left to right?

Quick quiz 2 / 3

In <div style="display:flex"><p>A</p><p>B</p></div> the div has height: 200px and the paragraphs have no height. How tall is each p?

Quick quiz 3 / 3

Which layout suits grid better than flexbox?

What to remember

  • display: flex turns only the direct children into flex items.
  • flex-direction picks the main axis; the cross axis is perpendicular to it.
  • justify-content owns the main axis and align-items the cross axis, whatever the direction.
  • Choose flex for layouts along one axis and grid when rows and columns must both line up.

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.

Flexbox Intro | Thuta Learning