Skip to main content
⚡ OpenDevDocs
CSS
frontendcssGuideBeginner

CSS Flexbox Layout

Mastering one-dimensional Flexbox: flex-direction, justify-content, align-items, flex-wrap, flex-grow, flex-shrink, and centering elements.

Verified: 2026-09-30
Platforms:
web
#css#flexbox#layout#alignment#web

CSS Flexbox Layout

Flexbox (Flexible Box Layout) is a one-dimensional layout model designed for distributing space and aligning items along either a row (horizontal) or a column (vertical).


1. Flex Container vs. Flex Items

Activating display: flex turns the parent into a flex container and its direct children into flex items:

[ Main Axis (justify-content) ] ────────────────────────►
┌───────────────────────────────────────────────────────┐
│  ┌──────────┐      ┌──────────┐      ┌──────────┐     │ ▲
│  │  Item 1  │      │  Item 2  │      │  Item 3  │     │ │ Cross Axis
│  └──────────┘      └──────────┘      └──────────┘     │ │ (align-items)
└───────────────────────────────────────────────────────┘ ▼

2. Container Properties

PropertyValuesPurpose
flex-directionrow (default), column, row-reverse, column-reverseSets the main axis orientation.
justify-contentflex-start, center, flex-end, space-between, space-around, space-evenlyAligns items along the main axis.
align-itemsstretch (default), center, flex-start, flex-end, baselineAligns items along the cross axis.
flex-wrapnowrap (default), wrap, wrap-reverseAllows items to wrap onto multiple lines.
gape.g. 1rem or 16px 24pxSets gutters between items without margins.

3. The Perfect Centering Solution

Centering both vertically and horizontally in pure CSS:

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

4. Item Properties (flex-grow, flex-shrink, flex-basis)

  • flex-grow: Proportion of leftover space the item should absorb (e.g. 1).
  • flex-shrink: Rate at which the item shrinks when space is constrained (default 1, set 0 to prevent shrinking).
  • flex-basis: Default initial size before space distribution (auto or 200px).

Shorthand:

/* flex: <flex-grow> <flex-shrink> <flex-basis> */
.sidebar {
  flex: 0 0 260px; /* Never grow, never shrink, always 260px */
}

.main-content {
  flex: 1 1 auto;  /* Grow to fill all remaining space */
}

On this page