Flexbox Axes & Alignment Matrix

Flexbox Axes & Alignment Matrix in CSS: CSS Flexible Box Layout (Flexbox) is a one-dimensional layout algorithm designed to distribute space and align items…

CSS Flexible Box Layout (Flexbox) is a one-dimensional layout algorithm designed to distribute space and align items along a primary axis. It automatically adapts to variable screen dimensions and dynamic content sizes.


The Two Axes of Flexbox

Every flex layout is defined by two perpendicular axes:

flex-direction: row (Default)
  Main Axis:  ============================> (Inline / Horizontal)
  Cross Axis: ||
              || (Block / Vertical)
              \/

flex-direction: column
  Main Axis:  || (Block / Vertical)
  Cross Axis: ============================> (Inline / Horizontal)
  • Main Axis: Established by flex-direction (row, row-reverse, column, column-reverse).
  • Cross Axis: Runs perpendicular to the Main Axis.

The Complete Alignment Property Matrix

PropertyGoverns Which Axis?Applied To?Key Values
justify-contentMain AxisContainerflex-start, flex-end, center, space-between, space-around, space-evenly
align-itemsCross Axis (Single line)Containerstretch (default), center, flex-start, flex-end, baseline
align-contentCross Axis (Multi-line)Containerstretch, center, space-between, space-around (Active only when flex-wrap: wrap creates multiple lines)
align-selfCross Axis (Single item)ItemOverrides the container's align-items for one specific child element
.flex-parent {
  display: flex;
  flex-direction: row;
  justify-content: space-between; /* Items pushed to opposite edges */
  align-items: center;            /* Centered vertically along cross axis */
  flex-wrap: wrap;                /* Wraps onto next row if container runs out of room */
  gap: 1.5rem;                    /* Spacing between items without margin resets */
}

The Centering Holy Grail

Before Flexbox, centering an element both horizontally and vertically required complex positioning hacks or table simulations. With Flexbox, it is two lines:

.perfect-center {
  display: flex;
  justify-content: center; /* Main axis center */
  align-items: center;     /* Cross axis center */
  min-height: 100vh;
}

The Power of margin: auto in Flexbox

In Flexbox, applying margin: auto (or margin-left: auto) to a flex child absorbs all remaining available free space on the main axis. This eliminates the need for empty spacer divs in navigation headers:

.navbar {
  display: flex;
  align-items: center;
}

.logo {
  font-weight: bold;
}

/* Pushes all subsequent nav items to the far right! */
.nav-menu {
  margin-inline-start: auto;
}

Exercises

  1. Build a card header with a title on the left and an action button pushed to the far right using margin-inline-start: auto.
  2. Demonstrate how align-items: baseline aligns elements with differing font sizes along their typographic baseline.
  3. Compare space-between, space-around, and space-evenly using a 3-item flex container.