CPCODELAB
CSS

Flexbox: One-Dimensional Layout

12 min read

Introducing Flexbox

Flexbox is a one-dimensional layout model — it lays items out either in a row or a column. It solves alignment problems that were painful before: centering things, distributing space evenly, and making items the same height.

css
.flex-container {
  display: flex;

  /* Direction — row (default) or column */
  flex-direction: row;

  /* Wrap onto new lines */
  flex-wrap: wrap;

  /* Shorthand for direction + wrap */
  flex-flow: row wrap;

  /* Alignment along the main axis (horizontal for row) */
  justify-content: space-between;

  /* Alignment along the cross axis (vertical for row) */
  align-items: center;

  /* Multi-line cross-axis alignment */
  align-content: flex-start;

  gap: 1rem;
}

Flex Children

css
.flex-item {
  /* flex-grow flex-shrink flex-basis */
  flex: 1 1 200px;

  /* Or use shorthand keywords */
  flex: 1;    /* grow and shrink freely, basis 0 */
  flex: auto; /* grow and shrink, basis auto */
  flex: none; /* don't grow or shrink */

  /* Override cross-axis alignment for a single item */
  align-self: flex-end;

  /* Reorder visually without changing the DOM */
  order: -1;
}

Centering something with Flexbox is two lines: display: flex; justify-content: center; align-items: center; on the parent. This was one of the hardest problems in pre-Flexbox CSS.

Ready to test yourself?
Practice CSS— quiz & coding exercises