Skip to content
Home
CSS Flexbox: The Complete Guide with Examples

CSS Flexbox: The Complete Guide with Examples

Web Development Web Development 8 min read 1612 words Beginner ExcellentWiki Editorial Team

Flexbox is the modern one-dimensional layout model in CSS. It replaces float-based layouts with simpler, more predictable code. Flexbox excels at distributing space, aligning items, and creating responsive layouts without the complexity of CSS Grid for single-axis arrangements.

The Flex Container

.container {
  display: flex;
---

This enables flex context for all direct children. Once display: flex is applied, the container gains access to powerful alignment and distribution properties that don’t exist in block or inline layout modes.

How Flexbox Changed CSS Layout

Before Flexbox, developers relied on float for multi-column layouts, which required clearfix hacks, often broke with dynamic content, and couldn’t vertically center items without complex calculations. display: table was workable but rigid. Flexbox solved all these problems with a single property: display: flex.

Browser support is universal — Flexbox works in every modern browser and IE11 (with some prefixing). It’s the safe default for any new layout work.

Main Axis vs Cross Axis

Flexbox works along two axes:

  • Main axis — direction set by flex-direction (default: row, left to right)
  • Cross axis — perpendicular to main axis

Understanding Axes Through Examples

When flex-direction: row, the main axis runs horizontally and justify-content controls horizontal alignment. When flex-direction: column, the main axis runs vertically and justify-content controls vertical alignment. This mental model is the key to mastering Flexbox.

/* Main axis = horizontal */
.row-layout {
  display: flex;
  flex-direction: row; /* default */
  justify-content: center; /* horizontal centering */
  align-items: center;     /* vertical centering */
---

/* Main axis = vertical */
.column-layout {
  display: flex;
  flex-direction: column;
  justify-content: center; /* vertical centering */
  align-items: center;     /* horizontal centering */
---

Swapping flex-direction swaps which axis justify-content and align-items affect. This is the most common source of confusion for Flexbox beginners.

Key Properties

On the Parent

PropertyOptionsWhat It Does
flex-directionrow (default), column, row-reverse, column-reverseSets main axis direction
justify-contentflex-start, center, space-between, space-around, space-evenlyAligns items along main axis
align-itemsstretch, center, flex-start, flex-end, baselineAligns items along cross axis
flex-wrapnowrap, wrap, wrap-reverseAllows items to wrap to next line
gapany CSS lengthSpacing between items

On the Children

PropertyWhat It Does
flex-growHow much the item grows relative to siblings
flex-shrinkHow much the item shrinks relative to siblings
flex-basisInitial size before growing or shrinking
align-selfOverrides parent’s align-items for this item
orderChanges visual order (default 0)

Understanding the Flex Shorthand

The flex property combines flex-grow, flex-shrink, and flex-basis:

.item {
  flex: 1;           /* flex-grow: 1, flex-shrink: 1, flex-basis: 0 */
  flex: 1 1 300px;   /* grow: 1, shrink: 1, basis: 300px */
  flex: 0 0 auto;    /* no grow, no shrink, use content width */
  flex: none;        /* flex: 0 0 auto - item stays its natural size */
---

The shorthand flex: 1 is the most common pattern. It tells the item to take up all available space equally among siblings with flex: 1. This is how you create equal-width columns, fill remaining space, or distribute a flex container across the viewport.

Gap vs Margins

The gap property (introduced in Flexbox in 2021) replaces the need for negative margins or complex selector chains for spacing. It’s supported in all modern browsers:

/* Old way - fragile and verbose */
.container {
  display: flex;
---
.container > * + * {
  margin-left: 1rem;
---

/* New way - clean and robust */
.container {
  display: flex;
  gap: 1rem;
---

Gap applies between items only, not before the first or after the last item, making it ideal for lists, nav bars, and card grids.

Common Layouts

Navigation Bar

.nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
---

Responsive Nav with Wrapping

For navigation bars that need to handle narrow screens:

.nav {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 1rem;
---

.nav a {
  flex: 0 0 auto;
  padding: 0.5rem 1rem;
---

When the screen narrows enough that links don’t fit on one line, flex-wrap: wrap pushes overflow items to the next row. This creates a responsive nav without media queries.

Card Grid

.grid {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
---

.card {
  flex: 1 1 300px;
---

How the Card Grid Works

Each card starts at a base width of 300px (flex-basis: 300px). If there’s extra space, all cards grow equally (flex-grow: 1) to fill the row. If the container is less than 300px + gaps wide, cards shrink (flex-shrink: 1) but won’t go below their content size. When cards no longer fit on one row, flex-wrap: wrap moves them to the next row.

By adjusting the flex-basis, you control the minimum comfortable card width. For a 3-column grid on desktop and 1-column on mobile, set flex-basis: 30% or use a media query to switch between flex-basis values.

Centered Content

.center {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
---

This combination is the modern solution to the classic “how do I center a div?” problem. It works regardless of content size, doesn’t require knowing dimensions, and adapts to dynamic content.

Holy Grail Layout

body {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
---

main {
  display: flex;
  flex: 1;
---

nav, aside {
  flex: 0 0 200px;
---

article {
  flex: 1;
---

The “Holy Grail” layout (header, footer, and three columns) was notoriously difficult with floats. With Flexbox, it’s straightforward. The body is a column flex container that fills the viewport. The main area is a row flex container where the nav and aside have fixed widths and the article fills remaining space. The footer stays at the bottom because main has flex: 1.

Sticky Footer Pattern

A common variation: ensure the footer is always at the bottom, even with minimal content:

body {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
---

.content {
  flex: 1; /* pushes footer to bottom */
---

footer {
  flex-shrink: 0;
---

Without Flexbox, achieving a sticky footer required 100+ height hacks or JavaScript. Flexbox solves it in 3 lines.

Flexbox vs Grid

FlexboxCSS Grid
One-dimensional (row OR column)Two-dimensional (row AND column)
Content-drivenLayout-driven
Best for nav bars, centering, small componentsBest for page layouts, complex grids

When to Reach for Each

Use Flexbox when:

  • You need to align items along a single axis
  • You want items to wrap naturally without specifying exact positions
  • The content determines the layout (e.g., a nav with variable-length links)
  • You need centering, equal spacing, or reverse ordering

Use Grid when:

  • You need a two-dimensional layout (rows and columns simultaneously)
  • You want explicit control over item placement (overlapping, spanning)
  • The layout determines where content goes (e.g., a magazine-style layout)
  • You’re creating a full page template

Many modern designs use both — Grid for the overall page layout and Flexbox for individual components within each grid cell.


Start with centering: See our guide on how to center a div.

Next: Learn CSS Grid, responsive design, and HTML semantic tags.

Flexbox Sizing Properties

Understanding flex-grow, flex-shrink, and flex-basis is essential for mastering flexbox layouts. flex-basis sets the initial main size before growing or shrinking. flex-grow distributes extra space among flex items proportionally. flex-shrink determines how items shrink when the container is too small. The shorthand flex: 1 means flex-grow: 1; flex-shrink: 1; flex-basis: 0; — the item can grow and shrink from zero, making all items equal width regardless of content. flex: auto uses flex-basis: auto, sizing items based on content.

Auto Margins in Flexbox

Auto margins (margin-left: auto) absorb remaining space in flex containers, pushing items apart. This is a one-line flexbox alignment trick: in a navigation bar, margin-left: auto on the last item pushes it to the right edge. Multiple auto margins distribute space between items. This technique replaces complex nested flex containers for simple alignment needs.

Web Performance Metrics

Understanding performance metrics helps prioritize optimization efforts. First Contentful Paint (FCP): when the first text or image appears — target under 1.8 seconds. Largest Contentful Paint (LCP): when the main content loads — target under 2.5 seconds. Interaction to Next Paint (INP): responsiveness to user interactions — target under 200 milliseconds. Cumulative Layout Shift (CLS): visual stability — target under 0.1. First Input Delay (FID): time to first interaction — target under 100 milliseconds. Time to First Byte (TTFB): server response time — target under 800 milliseconds. Use Google’s Lighthouse, WebPageTest, and Chrome DevTools to measure these metrics. Real User Monitoring (RUM) captures actual user experiences, which may differ from synthetic tests. Set up dashboards tracking Core Web Vitals and alert when thresholds are breached.

Accessibility Beyond Compliance

Web accessibility ensures your site works for everyone, including people using screen readers, keyboard navigation, or other assistive technologies. WCAG 2.2 guidelines organize requirements into four principles: Perceivable (content must be available to senses), Operable (interface must be usable), Understandable (content and interface must be comprehensible), and Robust (content must work with current and future technologies). Practical steps: use semantic HTML elements (nav, main, aside, article), provide alt text for images, ensure color contrast ratios meet WCAG AA standards (4.5:1 for normal text), support keyboard navigation with visible focus indicators, and test with screen readers (NVDA, VoiceOver, JAWS). Accessibility benefits everyone — captions help users in noisy environments, keyboard navigation helps users with repetitive strain injuries, and high contrast helps users in bright sunlight.

FAQ

What level of expertise is required? The content assumes basic programming knowledge but explains concepts in depth. Beginners may need to reference prerequisite topics.

How do I know if I am implementing this correctly? Write tests that verify behavior, use linters and static analysis, and get code reviews from experienced practitioners.

What are the most common pitfalls? Over-engineering, premature optimization, and neglecting testing are the most frequent mistakes. Start simple, measure, and iterate.

Section: Web Development 1612 words 8 min read Beginner 756 articles in section Report inaccuracy Back to top