Beginner30 min read

Flexbox Layout

Learn CSS Flexbox to create powerful one-dimensional layouts. Master flex containers, direction, alignment, wrapping, and the gap property to build responsive UI patterns with ease.

Flex Containers and Items

Flexbox is a one-dimensional layout system that lets you distribute space and align items along a single axis — either a row or a column.

To start using Flexbox, set display: flex on a container element. All direct children of that container automatically become flex items.

css
.container {
  display: flex;
}

By default, flex items are laid out in a row (left to right) and they try to fit onto a single line. Each item is sized based on its content, but Flexbox gives you powerful controls to change this behavior.

Key concepts:

  • Main axis — The primary axis along which flex items are placed (horizontal by default).
  • Cross axis — The perpendicular axis (vertical by default).
  • flex-direction controls the main axis direction: row (default), row-reverse, column, or column-reverse.

Alignment and Justification

css
.container {
  display: flex;

  /* Align items along the MAIN axis */
  justify-content: center;
  /* Options: flex-start | flex-end | center |
             space-between | space-around | space-evenly */

  /* Align items along the CROSS axis */
  align-items: center;
  /* Options: stretch | flex-start | flex-end |
             center | baseline */

  /* Allow items to wrap onto multiple lines */
  flex-wrap: wrap;

  /* Add spacing between items */
  gap: 16px;
}

The flex Shorthand

The flex shorthand property on flex items controls how they grow, shrink, and their base size. It combines three properties:

css
.item {
  flex: <flex-grow> <flex-shrink> <flex-basis>;
}
  • flex-grow — How much the item should grow relative to siblings when extra space is available. 0 means don't grow; 1 means take an equal share.
  • flex-shrink — How much the item should shrink when space is limited. 0 means don't shrink.
  • flex-basis — The initial size before growing or shrinking. Can be a length (200px) or auto.

Common shorthand values:

css
.item { flex: 1; }          /* grow: 1, shrink: 1, basis: 0% — equal sizing */
.item { flex: 0 0 200px; }  /* fixed at 200px, no grow or shrink */
.item { flex: 2 1 auto; }   /* grows twice as fast, shrinks normally */

Using flex: 1 on all items is a quick way to make them share the available space equally.

Which property controls the spacing between flex items without adding margin to the items themselves?

Ready to practice?

Create your free account to access the interactive code editor, run challenges, and track your progress.