Learn/HTML, CSS & JS/6. Layout with Flexbox
Lesson 6 of 8
Sign in

HTML, CSS & JS, lesson 6

Layout with Flexbox

By default, block elements stack top to bottom. To put things side by side, center them, or share space between them, use Flexbox.

Flex containers

Set display: flex on a parent. Its direct children become flex items and line up in a row:

gap adds space between items (not at the edges), which is cleaner than margins.

Direction and alignment

  • flex-direction: row (default) or column sets the main axis.
  • justify-content places items along the main axis: flex-start, center, flex-end, space-between, .

2 exercises to try what you just read.

Exercise 1

Navigation bar

Press Ctrl Enter or Check to test your code.

Exercise 2

Centered badge

Press Ctrl Enter or Check to test your code.

space-around
  • align-items places items across it: stretch (default), center, flex-start, flex-end.
  • So centering something in a box is:

    Growing and wrapping

    flex: 1 on an item tells it to take up the remaining space. Give two items flex: 1 and they share it equally. flex-wrap: wrap lets items move to a new line when they run out of room, which is the simplest way to make a row of cards responsive.

    Further reading

    • MDN: Flexbox
    • MDN: justify-content

    Style the page so that:

    1. .nav is a flex container whose items are spread out with justify-content: space-between and vertically centered (align-items: center).
    2. .links is also a flex container with a gap of 16px.

    Center the .badge both horizontally and vertically inside .stage using Flexbox on .stage.

    .menu {
      display: flex;
      gap: 12px;
    }
    .center-me {
      display: flex;
      justify-content: center;
      align-items: center;
    }