CodeOath
← All posts
HTML & CSS70 min total · 18 parts

CSS Fundamentals: The Box Model, Specificity, Positioning, and Layout

Contents — Part 12 of 18: Flexbox In Depth
Part 12 of 18 · ~1 min

Flexbox In Depth

Flexbox lays out children along a single axis — either a row or a column — and excels at distributing and aligning items along it.

.toolbar {
  display: flex;
  justify-content: space-between; /* main-axis alignment */
  align-items: center;            /* cross-axis alignment */
  gap: 12px;                      /* space between items — doesn't collapse like margins */
}

The two alignment properties are easy to mix up because which axis is "main" depends on flex-direction:

PropertyControlsCommon values
flex-directionWhich axis is the main axisrow (default), column, row-reverse, column-reverse
justify-contentAlignment along the main axisflex-start, center, space-between, space-around
align-itemsAlignment along the cross axisstretch (default), center, flex-start, flex-end
flex-wrapWhether items wrap onto new linesnowrap (default), wrap

Each individual flex item can also control how it grows or shrinks relative to its siblings:

.sidebar { flex: 0 0 250px; } /* don't grow, don't shrink, base width 250px */
.main    { flex: 1; }         /* grow to fill remaining space — shorthand for flex: 1 1 0% */

flex is shorthand for flex-grow flex-shrink flex-basis. flex: 1 on .main and a fixed flex: 0 0 250px on .sidebar is the standard pattern for a sidebar layout where the sidebar stays a fixed width and the main content fills whatever space is left — no width math required.