Lesson 6 / 1250%

Lesson 6

Flexbox

30 min

Align and distribute elements along an axis using Flexbox.

Definition

Flexbox (“Flexible Box Layout”) is a CSS layout module that lets you arrange, align and distribute space between several elements along an axis, even when their size is not known in advance or changes depending on the screen. An element becomes aflex container with display: flex;, and its direct children become flex items.

Enabling Flexbox

Flexbox is a layout system designed to align elements along a single axis(horizontal or vertical). You enable it on a container withdisplay: flex;: all of its direct children then become “flex items”.

flex-base.css
.container {
  display: flex;
}
flex-base.html
<div class="container">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
</div>
<!-- The 3 divs automatically line up side by side -->

Understanding the two axes

All of Flexbox relies on two perpendicular axes. The main axis is the one along which the items follow one another; the cross axis is perpendicular to it. By default, the main axis is horizontal (left to right) and the cross axis is vertical. If you switch to a column with flex-direction: column, the two axes swap: this is the source of many misunderstandings.

  • Main axis — controlled by justify-content. In a row: horizontal; in a column: vertical.
  • Cross axis — controlled by align-items. In a row: vertical; in a column: horizontal.

The direction: flex-direction

flex-direction.css
.row { flex-direction: row; }         /* default: left to right */
.row-reversed { flex-direction: row-reverse; }
.column { flex-direction: column; }     /* top to bottom */
.column-reversed { flex-direction: column-reverse; }

The two properties flex-direction and flex-wrap can be written on a single line with the flex-flow shorthand: the direction first, then the wrapping.

flex-flow.css
.container {
  display: flex;
  flex-flow: column wrap; /* equivalent to flex-direction: column + flex-wrap: wrap */
}

Aligning on the main axis: justify-content

justify-content.css
.container {
  display: flex;
  justify-content: flex-start;    /* default: at the start */
  justify-content: flex-end;      /* at the end */
  justify-content: center;        /* centered */
  justify-content: space-between; /* first and last items touch the edges, equal space between */
  justify-content: space-around;  /* equal space around each item */
  justify-content: space-evenly;  /* perfectly equal space everywhere */
}

Aligning on the cross axis: align-items

align-items.css
.container {
  display: flex;
  height: 200px;
  align-items: stretch;    /* default: stretches the items to the full height */
  align-items: flex-start; /* aligns at the top */
  align-items: flex-end;   /* aligns at the bottom */
  align-items: center;     /* centers vertically */
}

The combo to remember

To perfectly center an element both horizontally AND vertically — a very common need — the magic combination is:

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

Wrapping: flex-wrap

By default, Flexbox tries to fit all the items on a single line, even if it has to shrink them. flex-wrapallows the items to wrap onto new lines.

flex-wrap.css
.container {
  display: flex;
  flex-wrap: wrap; /* items move to the next line if needed */
  gap: 16px;       /* space between items, horizontal AND vertical */
}

Distributing multiple lines: align-content

When flex-wrap: wrap creates several lines, align-content decides how those lines are distributed along the cross axis, much likejustify-content does for items. It only has an effect if the container has extra height to share and contains several lines.

align-content.css
.container {
  display: flex;
  flex-wrap: wrap;
  height: 400px;
  align-content: flex-start;     /* the lines group together at the top */
  align-content: center;         /* the lines group together in the middle */
  align-content: space-between;  /* first and last lines touch the edges */
}

Controlling each item individually

Some properties apply to the children rather than to the container.

flex-items.css
.card {
  flex: 1; /* grows and shrinks to fill the available space, equally */
}

.wide-card {
  flex: 2; /* takes up twice as much space as .card (flex: 1) */
}

.fixed-card {
  flex: 0 0 200px; /* doesn't grow, doesn't shrink, fixed width of 200px */
}

.last-to-first {
  order: -1; /* moves visually to the first position, without changing the HTML order */
}

.self-centered {
  align-self: center; /* overrides the parent's align-items, for this item only */
}
  • flex: 1 — a widely used shorthand for “take up the remaining space, equally among several items”.
  • gap — much simpler than manually adding margins between each item.
  • order — changes the visual order without touching the HTML (useful for responsive design, but keyboard navigation still follows the HTML order).

Breaking down flex: grow, shrink and basis

The flex shorthand actually hides three properties, written in this order:flex-grow (ability to grow), flex-shrink (ability to shrink) andflex-basis (starting size, before the space is distributed). Understanding this mechanism lets you predict precisely how items share the available room.

grow-shrink-basis.css
.item {
  flex-grow: 1;      /* receives a share of the free space */
  flex-shrink: 1;    /* agrees to shrink if space runs short */
  flex-basis: 200px; /* desired starting size */
}

/* Equivalent shorthand: */
.item {
  flex: 1 1 200px;
}
  • flex: 1 is equivalent to 1 1 0: all items start from zero and share the space equally.
  • flex: 0 0 200px: strictly fixed size, neither larger nor smaller.
  • flex: auto: the item starts from its natural size, then grows or shrinks depending on the space.

The auto margin trick

In a flex container, an auto margin absorbs all the free space on its side. It’s a very simple way to push an item to the opposite end, without touching the others.

auto-margin.css
.navbar {
  display: flex;
  align-items: center;
}

.navbar .login {
  margin-left: auto; /* pushes this button all the way to the right of the bar */
}

Watch out: overflowing items

A flex item never shrinks below the size of its content. If a long piece of text or an image makes your layout overflow, add min-width: 0; to the child in question to allow it to shrink further.

Debugging with browser tools

In the inspector, a small “flex” badge appears next to each flex container. Clicking it overlays a grid showing the axes, the gaps and the size of each item: very handy for understanding why an alignment isn’t behaving as expected.

Full example: a navigation bar

navbar.html
<nav class="navbar">
  <div class="logo">MySite</div>
  <ul class="links">
    <li><a href="/">Home</a></li>
    <li><a href="/services">Services</a></li>
    <li><a href="/contact">Contact</a></li>
  </ul>
</nav>
navbar.css
.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background-color: #1e1b4b;
}

.links {
  display: flex;
  gap: 20px;
  margin: 0;
  padding: 0;        /* removes the list's default indentation */
  list-style: none;
}

.links a {
  color: white;
  text-decoration: none;
}
Flexbox in CSS

Full example: a responsive card grid

With flex-wrap, gap and a reasonable flex-basis, you get, without any media query, a row of cards that automatically wraps depending on the screen width. It’s one of the most useful Flexbox patterns.

cards.html
<div class="cards">
  <div class="card">Card 1</div>
  <div class="card">Card 2</div>
  <div class="card">Card 3</div>
  <div class="card">Card 4</div>
</div>
cards.css
.cards {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.card {
  flex: 1 1 250px;   /* starts at 250px, grows to fill the line, shrinks if needed */
  padding: 20px;
  border: 1px solid #ddd6fe;
  border-radius: 12px;
}

Flexbox or Grid?

Flexbox is designed to organize items in one dimension: one row or one column at a time. As soon as you want to control rows and columns simultaneously (a real page grid, for example), CSS Grid becomes more suitable. The two tools complement each other and are often used together on the same page.

Exercise

Create a row of 3 cards with display: flex;, equal spacing between them with gap, and center the whole thing horizontally with justify-content: center;.

Exercise: the axes

Create a container with 3 boxes, then switch from flex-direction: rowto column. Observe whatjustify-content andalign-items do in each case.

Exercise: auto margins

In a navigation bar, place the logo and two links on the left, then push a “Log in” button all the way to the right with margin-left: auto;.

Going further

Build a complete navigation bar (logo on the left, links on the right) like the example above, then add flex-wrap: wrap;so that it wraps correctly onto two lines on a narrow screen.