CSS layout was painful before Flexbox and Grid. Float-based layouts, clearfix hacks, and table display tricks. Today, Flexbox and Grid solve 99% of layout problems elegantly — but most developers only know 20% of what each system offers. This guide covers every property with practical examples and the patterns you reach for every day.
⚡ TL;DR: Flexbox is one-dimensional (row OR column). Grid is two-dimensional (rows AND columns). Use Flexbox for components and small-scale layouts. Use Grid for page-level layouts and precise two-axis control. Use both together — they are not competing.
Flexbox — the mental model
/* Flex container: controls how children are laid out */
.container {
display: flex;
flex-direction: row; /* row | row-reverse | column | column-reverse */
flex-wrap: wrap; /* nowrap | wrap | wrap-reverse */
justify-content: space-between; /* Main axis alignment */
align-items: center; /* Cross axis alignment */
align-content: stretch; /* Multi-line cross axis */
gap: 16px; /* Space between items (shorthand for row-gap column-gap) */
}
/* justify-content values:
flex-start | flex-end | center |
space-between | space-around | space-evenly */
/* align-items values:
flex-start | flex-end | center |
stretch (default) | baseline */Flex children properties
/* flex-grow: how much to grow relative to siblings */
.item { flex-grow: 1; } /* All items grow equally, filling container */
.sidebar { flex-grow: 0; } /* Stays at content size */
.main { flex-grow: 3; } /* Gets 3x more space than flex-grow:1 siblings */
/* flex-shrink: how much to shrink when container is too small */
.item { flex-shrink: 1; } /* Default: shrinks proportionally */
.item { flex-shrink: 0; } /* Never shrinks — useful for fixed-size items */
/* flex-basis: starting size before grow/shrink applies */
.item { flex-basis: 200px; } /* Start at 200px, then grow/shrink */
.item { flex-basis: auto; } /* Use content size as starting point */
/* Shorthand: flex: grow shrink basis */
.item { flex: 1 1 auto; } /* Grow, shrink, auto basis — most common */
.item { flex: 1; } /* flex: 1 1 0 */
.item { flex: none; } /* flex: 0 0 auto — fixed size */
/* align-self: override container's align-items for one item */
.special { align-self: flex-end; }
/* order: visual reordering without changing DOM */
.first { order: -1; } /* Move to front visually */Common Flexbox patterns
/* 1. Perfect center (most searched CSS question ever) */
.center {
display: flex;
justify-content: center;
align-items: center;
}
/* 2. Navbar: logo left, nav right */
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
}
/* 3. Card with footer pinned to bottom */
.card {
display: flex;
flex-direction: column;
height: 300px;
}
.card-content { flex: 1; } /* Grows to fill space */
.card-footer { /* Stays at bottom */ }
/* 4. Responsive wrapping grid */
.flex-grid {
display: flex;
flex-wrap: wrap;
gap: 16px;
}
.flex-grid > * {
flex: 1 1 250px; /* At least 250px wide, grows to fill */
}CSS Grid — the mental model
/* Define tracks with grid-template-columns and rows */
.grid {
display: grid;
grid-template-columns: 200px 1fr 1fr; /* 3 columns: fixed + 2 flexible */
grid-template-rows: auto; /* Rows size to content */
gap: 24px; /* Space between cells */
}
/* fr unit: fraction of available space */
/* 1fr 2fr 1fr = 25% 50% 25% of space */
/* repeat() shorthand */
grid-template-columns: repeat(3, 1fr); /* 3 equal columns */
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); /* Responsive! */
/* auto-fill: creates as many tracks as fit
minmax(250px, 1fr): each at least 250px, max 1fr
Result: responsive grid WITHOUT media queries */Grid placement and template areas
/* Named template areas — most readable grid layout */
.layout {
display: grid;
grid-template-areas:
"header header header"
"sidebar main main "
"footer footer footer";
grid-template-columns: 250px 1fr 1fr;
grid-template-rows: 60px 1fr 50px;
min-height: 100vh;
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }
/* Explicit placement with line numbers */
.item {
grid-column: 1 / 3; /* Span from line 1 to line 3 (2 columns) */
grid-row: 1 / 2; /* Single row */
}
.item {
grid-column: 1 / -1; /* Span all columns (-1 = last line) */
grid-row: span 2; /* Span 2 rows from current position */
}Advanced Grid: responsive without media queries, named lines and subgrid
Three Grid features remove most layout media queries. repeat(auto-fill, minmax(...)) creates as many columns as fit, each at least the minimum width, and wraps the rest. auto-fit does the same but collapses empty tracks, so when there are fewer items than columns they stretch to fill the row. Wrapping the minimum in min(16rem, 100%) stops a single column from overflowing on very narrow screens.
/* Cards wrap to as many columns as fit, each at least 16rem wide. No media query. */
.cards {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(min(16rem, 100%), 1fr));
gap: 1.5rem;
}
/* auto-fit collapses empty tracks, so a short row of items stretches to fill the width. */
.cards--stretch {
grid-template-columns: repeat(auto-fit, minmax(min(16rem, 100%), 1fr));
}
/* Named lines: place items by meaning instead of by column number. */
.page {
display: grid;
grid-template-columns: [full-start] minmax(1rem, 1fr) [content-start] minmax(0, 65ch) [content-end] minmax(1rem, 1fr) [full-end];
}
.page > * { grid-column: content; } /* uses content-start / content-end */
.page > .bleed { grid-column: full; } /* full-width banner or image */
/* Subgrid: each card's header, body and footer line up across the row. */
.card {
display: grid;
grid-row: span 3;
grid-template-rows: subgrid;
}Named lines let you place items by meaning. A pair named content-start and content-end can be referenced as grid-column: content, which keeps a readable text column with full-bleed images and banners in the same grid.
Subgrid lets a nested grid use its parent’s tracks. In the card example, each card spans three of the parent’s rows and adopts them with grid-template-rows: subgrid, so headings, bodies and footers line up across cards even when their text lengths differ. Subgrid is supported in current versions of all major browsers; check MDN’s subgrid page if you support older ones.
Flexbox vs Grid — when to use each
- ✅ Flexbox for: navigation bars, card rows, centering, one-dimensional alignment
- ✅ Grid for: page layouts, dashboard grids, precise two-dimensional positioning
- ✅ Both together: Grid for page structure, Flexbox for items within each grid area
- ✅ Responsive without media queries:
repeat(auto-fill, minmax(250px, 1fr)) - ❌ Don’t use Grid for simple one-dimensional alignment — Flexbox is simpler
- ❌ Don’t use float or position for layout — Flexbox/Grid replaced them
CSS layout knowledge connects directly to React performance optimization — understanding layout reflow costs helps you avoid expensive re-renders. External reference: CSS-Tricks Flexbox guide.
Free Weekly Newsletter
🚀 Don’t Miss the Next Cheat Code
Related: CSS Grid Advanced Patterns: Build Any Layout With Grid Template Areas · CSS Pseudo-Classes and Pseudo-Elements: The Complete Styling Guide · CSS Animations and Transitions: Performance-Optimized Motion for Modern UIs
Related: AI Test Generation: Property Tests That Catch Race Conditions · Time-Saving One-Liners Every Developer Should Know
Watch: 100 Days of AI on YouTube
Short videos from CheatCoders, one AI engineering topic per day.
Most viewed
- Python Decorators Explained: From Simple Wrappers to Production Patterns
- Claude Code vs Cursor vs GitHub Copilot: Choose by Workflow, and Set Up One Repo That Works With All Three
- AI Agent Frameworks in 2025: LangGraph vs CrewAI vs AutoGen vs Raw API
- Python String Methods: Every str Method With Real Production Examples
- REST API Design Best Practices: The Patterns That Make APIs a Joy to Use
Newly added
- AWS Systems Manager Parameter Store: Hierarchical Runtime Config for Coding Agents
- Amazon Cognito Identity Pools: Federate Coding-Agent Tool Callers Without Long-Lived Keys
- Amazon Athena for Coding Agents: Query Tool Audit Logs and Eval Traces on S3 Without a Warehouse
- AWS Batch for Coding Agents: Parallel Overnight PR Reviews and Long-Running Jobs Without Lambda Timeouts
- Amazon Bedrock Prompt Management: Version and A/B Test Coding-Agent System Prompts
Deep-dive PDF
Get the expanded guide for this post — extra diagrams-style checklists, failure modes, and a production walkthrough. Free when you subscribe to CheatCoders.
Already subscribed? or open the subscribe page.
Discover more from CheatCoders
Subscribe to get the latest posts sent to your email.
