Lesson 8 — Layout

Flexbox

Flexbox is a one-dimensional layout system designed for distributing space and aligning items along a row or a column, making common layout patterns dramatically simpler.

Getting Started With Flex

Setting display: flex on a container turns its direct children into flex items, which can then be aligned and spaced using a handful of powerful properties on the parent.

CSS — A flex row layout
.nav {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
}

.nav-links {
    display: flex;
    gap: 8px;
}

Key Flex Properties

A small set of properties covers the vast majority of real layout needs.

  • flex-direction — row (default) or column, sets the main axis.
  • justify-content — aligns items along the main axis (start, center, space-between...).
  • align-items — aligns items along the cross axis.
  • flex-wrap — allows items to wrap onto multiple lines instead of overflowing.
  • gap — sets consistent spacing between items without needing margin hacks.

Common Mistakes

  • Forgetting that justify-content works along the main axis while align-items works along the cross axis — swapping them by mistake is the most common flexbox confusion.
  • Not setting flex-wrap: wrap on a row that needs to reflow on smaller screens, causing horizontal overflow.
  • Using individual margins to fake spacing between flex items instead of the simpler gap property.
  • Applying flex properties to the child items when the property actually belongs on the parent container (like justify-content).

Professional Tip

Remember: flex-direction sets your main axis. In the default row direction, justify-content works left-to-right and align-items works top-to-bottom. Switch to flex-direction: column and those two swap roles.

Your Turn

Build a navigation bar using flexbox with a logo on the left, nav links in the centre area, and a button on the right, all vertically centred.

Mini Quiz

Which property aligns flex items along the main axis, such as spreading them apart in a row?