Flexbox, explained by moving boxes

Change flex-direction, justify-content, align-items, gap and flex-wrap with the controls and watch how the boxes lay out and what CSS it generates.

Flexbox lab

Flexbox lays elements out in a row or a column and distributes the space between them. The fastest way to get it is to touch the controls and watch.

The main axis and the cross axis

Everything in Flexbox revolves around two axes. With flex-direction: row the main axis is horizontal and the cross axis vertical. With column they swap.

Properties of the children

The ones above go on the container. These go on each child box:

.caja {
  flex-grow: 1;    /* reparte el espacio sobrante (0 = no crecer) */
  flex-shrink: 1;  /* se encoge si falta espacio */
  flex-basis: 200px; /* tamaño de partida antes de crecer/encoger */

  /* atajo habitual: */
  flex: 1;         /* = flex: 1 1 0  → todas iguales, ocupan todo */
}

.caja-especial {
  align-self: flex-end;  /* como align-items pero solo para esta caja */
}

Quick recipes

/* Centrar algo, del todo */
.centrado { display: flex; justify-content: center; align-items: center; }

/* Barra de navegación: logo a la izquierda, menú a la derecha */
.navbar { display: flex; justify-content: space-between; align-items: center; }

/* Fila de tarjetas que salta de línea sola */
.tarjetas { display: flex; flex-wrap: wrap; gap: 16px; }
.tarjetas > * { flex: 1 1 240px; }   /* mínimo 240px, luego crecen */

Next step

Flexbox is for one dimension (row or column). For two-dimensional grids at once, use CSS Grid. Review also CSS from the beginning.