Complete Guide to CSS Grid and Flexbox
Master CSS layout: Grid vs Flexbox, template areas, subgrid, container queries, logical properties and responsive patterns without media queries.
Introduction
CSS Grid and Flexbox replaced floats, tables, and positioning hacks as the way web layouts get built. Grid handles two-dimensional layouts — rows and columns at once. Flexbox handles one-dimensional distribution — a row or a column of items. Most real pages use both: Grid for the page skeleton, Flexbox inside components.
This guide covers both systems with working patterns: grid templates and named areas, subgrid, flex alignment, container queries, logical properties, and responsive layouts that need no media queries. Code samples assume nothing beyond plain CSS — no framework, no preprocessor.
A mental model that helps: Grid is a canvas — you define regions first and place things into them. Flexbox is a queue — items line up and share space along one direction. Once a layout problem is framed that way, the right tool usually picks itself. The harder skill is knowing how to combine them, which is why the guide ends with the mistakes teams repeat most often.
When to Use Grid vs Flexbox
The choice isn’t either/or — it’s about which axis you’re controlling:
| Situation | Tool | Why |
|---|---|---|
| Page skeleton (header/sidebar/main/footer) | Grid | 2D control over rows and columns |
| Card grids, dashboards, image galleries | Grid | Items must align in both directions |
| Named layout regions | Grid | grid-template-areas maps structure visually |
| Nav bars, toolbars, button groups | Flexbox | 1D distribution along one axis |
| Content-driven sizing inside a component | Flexbox | Items grow/shrink based on content |
| Centering or reordering items | Either | Both do it; Grid’s place-items is shorter |
| Component that adapts to its container | Container queries | Responds to parent size, not viewport |
The rule of thumb that holds up in practice: Grid for structure, Flexbox for content. A dashboard grid is Grid; the toolbar inside each card is Flexbox. For the mobile-first strategy around these choices, see the responsive design guide.
When neither applies: single-column text flows, multi-column for newspaper-style text, or inline-block for trivial cases — don’t reach for Grid just because it’s newer.
CSS Grid
Basic Grid
/* 3-column grid with gaps */
.card-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1.5rem;
}
/* Responsive without media queries */
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 1.5rem;
}
/* Fixed sidebar + fluid content */
.layout {
display: grid;
grid-template-columns: 250px 1fr;
min-height: 100vh;
}
repeat(auto-fill, minmax(280px, 1fr)) is the workhorse pattern — columns are added as space allows, no breakpoints needed. On very narrow screens minmax(280px, 1fr) can still overflow; the fix is minmax(min(100%, 280px), 1fr), covered in the responsive section.
auto-fill vs auto-fit: auto-fill keeps empty tracks so items keep their minimum size; auto-fit collapses them so existing items stretch to fill the row. Same code, different intent — pick per design.
Grid Template Areas
Named areas make the layout readable at a glance — the ASCII map is the structure:
.page-layout {
display: grid;
grid-template-areas:
"header header header"
"sidebar main aside"
"footer footer footer";
grid-template-columns: 200px 1fr 200px;
grid-template-rows: auto 1fr auto;
min-height: 100vh;
gap: 1rem;
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.aside { grid-area: aside; }
.footer { grid-area: footer; }
/* Responsive: stack on mobile */
@media (max-width: 768px) {
.page-layout {
grid-template-areas:
"header"
"main"
"sidebar"
"aside"
"footer";
grid-template-columns: 1fr;
}
}
<div class="page-layout">
<header class="header">Header</header>
<nav class="sidebar">Sidebar</nav>
<main class="main">Main content</main>
<aside class="aside">Aside</aside>
<footer class="footer">Footer</footer>
</div>
Redrawing the template inside a media query refactors the whole page layout by editing five strings — this is where Grid earns its keep vs stacking floats.
Span and line-based placement
.feature-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-rows: repeat(3, 200px);
gap: 1rem;
}
.featured { grid-column: span 2; grid-row: span 2; }
.wide { grid-column: 1 / -1; } /* full width */
.sidebar-item { grid-column: 4; grid-row: 1 / 4; } /* right column, full height */
Line numbers count from 1 at the start edge; -1 means the last line. span is usually safer than hardcoded line numbers because it survives grid changes and keeps the intent readable.
Subgrid
Subgrid lets a nested grid inherit the parent’s tracks — the fix for card grids where titles, images and prices must line up across cards of different heights:
.product-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 1rem;
}
.product-card {
display: grid;
grid-template-rows: subgrid;
grid-row: span 3; /* card spans 3 parent rows */
gap: 0;
}
.product-card .title { grid-row: 1; }
.product-card .image { grid-row: 2; }
.product-card .price { grid-row: 3; }
/* All titles align across cards, all images align, all prices align */
Before subgrid, this required fixed heights or JavaScript. It’s supported in all modern browsers (Chrome 117+, Firefox 71+, Safari 16+) — no graceful fallback for very old browsers, so use it for alignment, not for critical structure.
Grid Alignment
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1rem;
/* Align items along the block (row) axis */
align-items: start | center | end | stretch;
/* Align items along the inline (column) axis */
justify-items: start | center | end | stretch;
/* Align the whole grid within the container */
align-content: start | center | end | space-between | space-around;
justify-content: start | center | end | space-between | space-around;
}
/* Individual item alignment */
.grid-item {
align-self: center;
justify-self: end;
}
Axis names differ per system and trip people up: in Grid, align-* is the block (row) axis and justify-* is the inline (column) axis. place-items: center is the shorthand for both.
Common Grid Patterns
/* Holy Grail layout */
.holy-grail {
display: grid;
grid-template:
"header header header" auto
"nav main aside" 1fr
"footer footer footer" auto
/ 200px 1fr 200px;
min-height: 100vh;
gap: 1rem;
}
@media (max-width: 768px) {
.holy-grail {
grid-template:
"header" auto
"main" 1fr
"nav" auto
"aside" auto
"footer" auto
/ 1fr;
}
}
/* Center anything */
.center-anything {
display: grid;
place-items: center;
min-height: 100vh;
}
/* Sticky header + scrollable content */
.app-shell {
display: grid;
grid-template-rows: auto 1fr;
height: 100vh;
}
.app-header { position: sticky; top: 0; z-index: 10; }
.app-content { overflow-y: auto; }
/* Sticky sidebar + scrollable main */
.app-layout {
display: grid;
grid-template-columns: 280px 1fr;
height: 100vh;
}
.sidebar { overflow-y: auto; position: sticky; top: 0; height: 100vh; }
.main-content { overflow-y: auto; padding: 2rem; }
Masonry via grid-template-rows: masonry exists but remains experimental — ship it only behind a feature query, and keep a column-count or JavaScript-based fallback for older browsers.
Flexbox
Basic Flexbox
/* Horizontal navigation bar */
.navbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding: 0 1.5rem;
}
.nav-links {
display: flex;
gap: 1rem;
list-style: none;
}
/* Card with image, content, and action */
.card {
display: flex;
flex-direction: column;
gap: 1rem;
}
.card-image { width: 100%; aspect-ratio: 16 / 9; object-fit: cover; }
.card-content { flex: 1; } /* take remaining space */
.card-actions { display: flex; justify-content: flex-end; gap: 0.5rem; }
flex: 1 on .card-content is the classic pattern for equal-height cards: the content area stretches so action buttons line up at the bottom regardless of text length.
Flexbox Alignment
.flex-container {
display: flex;
/* Main axis alignment */
justify-content: flex-start | flex-end | center | space-between | space-around | space-evenly;
/* Cross axis alignment */
align-items: stretch | flex-start | center | flex-end | baseline;
/* Multi-line alignment (when wrapping) */
align-content: flex-start | center | flex-end | space-between | space-around;
/* Direction and wrapping */
flex-direction: row | row-reverse | column | column-reverse;
flex-wrap: nowrap | wrap | wrap-reverse;
gap: 1rem;
}
.flex-item {
align-self: flex-start | center | flex-end | stretch | baseline;
}
In Flexbox the axes flip with flex-direction: justify-content follows the main axis, align-items the cross axis. With flex-direction: column, justify-content now distributes vertically — a common source of “why doesn’t it center” confusion.
Flex Item Properties
.flex-item {
flex-grow: 0; /* default: don't grow */
flex-shrink: 1; /* default: may shrink */
flex-basis: auto; /* default: content size */
/* Shorthand: flex: grow shrink basis */
flex: 1; /* = 1 1 0% — equal distribution regardless of content */
flex: 2; /* = 2 1 0% — twice the share */
flex: auto; /* = 1 1 auto — grow from content size */
flex: none; /* = 0 0 auto — rigid item */
order: -1; /* move visually to front */
}
flex: 1 vs flex: auto is the distinction that matters: flex: 1 gives equal items regardless of content (basis: 0%), flex: auto respects content width first and splits only the leftover space. For grow/shrink ratios, think of flex: 0 0 48px (avatar) vs flex: 1 1 auto (message body) vs flex: 0 0 auto (timestamp).
Common Flexbox Patterns
/* Center anything */
.center {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
}
/* Sticky footer */
.page { display: flex; flex-direction: column; min-height: 100vh; }
.page-content { flex: 1; }
/* Input with attached button */
.input-group { display: flex; align-items: stretch; }
.input-group input { flex: 1; border-radius: 4px 0 0 4px; }
.input-group button { border-radius: 0 4px 4px 0; }
/* Media object (avatar + content) */
.media { display: flex; align-items: flex-start; gap: 1rem; }
.media-image { flex: 0 0 48px; width: 48px; height: 48px; border-radius: 50%; }
.media-body { flex: 1; }
/* Responsive wrap */
.tag-list { display: flex; flex-wrap: wrap; gap: 0.5rem; }
.tag { flex: 0 0 auto; padding: 0.25rem 0.75rem; border-radius: 9999px; }
Container Queries
Media queries respond to the viewport; container queries respond to the parent. A card can render side-by-side in the main column and stacked in the sidebar — same component, no knowledge of where it sits:
.card-wrapper {
container-type: inline-size;
container-name: card;
}
/* Styles apply based on the container's width, not the viewport */
@container card (min-width: 400px) {
.card {
display: grid;
grid-template-columns: 120px 1fr;
gap: 1rem;
}
}
@container card (max-width: 399px) {
.card {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
}
/* Container query units */
.card-title { font-size: clamp(1rem, 5cqi, 1.5rem); } /* cqi = container inline */
.card-image { height: 50cqh; } /* 50% of container height */
<!-- The same component adapts to where it's placed -->
<div class="sidebar" style="container-type: inline-size;">
<div class="card">...</div> <!-- narrow: stacked -->
</div>
This is the pattern that makes component libraries truly portable. For a focused recipe, see CSS container queries.
Logical Properties
Physical properties (margin-left, border-top) break under right-to-left writing modes. Logical properties track the writing direction instead:
/* Physical (direction-specific) */
.old-way {
margin-left: 1rem;
padding-top: 0.5rem;
text-align: left;
border-left: 1px solid #ccc;
}
/* Logical (direction-aware, RTL-safe) */
.new-way {
margin-inline: 1rem; /* left + right in LTR */
padding-block: 0.5rem; /* top + bottom */
text-align: start; /* left in LTR, right in RTL */
border-inline-start: 1px solid #ccc;
}
/* Logical sizing */
.sidebar {
inline-size: 250px; /* width */
block-size: 100vh; /* height */
max-inline-size: 100%; /* max-width */
}
Use logical properties by default on anything that touches edges — margins, padding, borders, text alignment. The cost is zero and RTL support comes free.
Responsive Design Patterns
/* Mobile-first grid with breakpoints */
.responsive-grid {
display: grid;
gap: 1rem;
grid-template-columns: 1fr;
}
@media (min-width: 640px) { .responsive-grid { grid-template-columns: repeat(2, 1fr); } }
@media (min-width: 1024px) { .responsive-grid { grid-template-columns: repeat(3, 1fr); } }
@media (min-width: 1280px) { .responsive-grid { grid-template-columns: repeat(4, 1fr); } }
/* Auto-fit grid — no media queries needed */
.auto-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 280px), 1fr));
gap: 1.5rem;
}
/* min(100%, 280px) prevents overflow on screens narrower than 280px */
/* Fluid typography with clamp() */
h1 { font-size: clamp(1.5rem, 4vw, 3rem); }
p { font-size: clamp(1rem, 2.5vw, 1.125rem); line-height: 1.6; }
/* Aspect ratio without padding hacks */
.video-embed { aspect-ratio: 16 / 9; width: 100%; }
.avatar-square { aspect-ratio: 1; width: 48px; object-fit: cover; }
Mobile-first breakpoints document the design’s intent; the auto-fit/minmax/min() combo removes most breakpoints entirely. Use both: intrinsic sizing for components, breakpoints for page-level structure.
A practical workflow: start with intrinsic layout (auto-fit grids, clamp() for type, aspect-ratio for media). Only add a breakpoint when the intrinsic approach can’t express the design — like reordering regions, hiding a sidebar, or switching a nav pattern. The result is a stylesheet where every media query is meaningful instead of a wall of min-width guesses that no one dares to touch.
Gap Property
/* Gap works identically in Grid and Flexbox */
.grid-layout {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1rem;
/* row-gap: 1rem; */
/* column-gap: 0.5rem; */
}
.flex-layout {
display: flex;
gap: 1rem;
/* row-gap: 0.5rem; */
/* column-gap: 1rem; */
}
/* Two-value gap: row-gap column-gap */
.flex-wrap-layout {
display: flex;
flex-wrap: wrap;
gap: 1rem 2rem;
}
gap replaced margin-based spacing: no edge double-spacing, no :first-child/last-child resets, no collapsing margins to fight. If an older codebase still spaces items with margins, migrating to gap is usually a safe first refactor.
Best Practices
- Grid for structure, Flexbox for content — page skeleton in Grid, component internals in Flexbox
- Mobile-first breakpoints — base styles for the smallest screen, enhance upward
- Use
min()insideminmax()—minmax(min(100%, 280px), 1fr)prevents overflow on tiny screens - Prefer
auto-fitoverauto-fillwhen items should stretch to fill the row - Use
gap, not margins — cleaner spacing with no edge effects - Use
clamp()for fluid type — kills most typography breakpoints - Logical properties by default —
margin-inline,padding-block,text-align: start - Container queries for components — components adapt to their slot, not the screen
aspect-ratioover padding hacks —16/9in one declaration- Subgrid for card alignment — aligned titles/images/prices across variable-height cards
- Visual order must match DOM order —
orderand grid placement can desynchronize keyboard/screen-reader navigation; reorder the HTML, not just the paint - Test at real widths — DevTools emulation at 320px, 768px, 1024px, 1440px
Common Mistakes
- Flexbox for 2D layouts — flex-wrap aligns items per row independently; use Grid when rows and columns must line up
orderfor visual reordering — breaks keyboard focus order and screen readers; reorder the DOM- Fixed pixel widths —
width: 300pxbreaks on resize; usefr,minmax(), percentages minmax(280px, 1fr)withoutmin()— overflows below 280px viewport100vhon mobile — mobile browsers include chrome invh; prefer100dvhormin-heightfallbacks- Media queries for component layout — a component that resizes by viewport ignores where it’s placed; container queries fix this
- Margins instead of
gap— edge double-spacing and margin collapse bugs - Forgetting
flex-basissemantics —flex: 1andflex: autodiffer when content sizes vary - Physical properties —
margin-leftbreaks in RTL; use logical properties overflow: hiddento fix float-era issues — with Grid/Flexbox it usually hides real overflow bugs instead of fixing them
See Also
- Complete Guide to Mobile Responsive Design — mobile-first strategy around these layout tools
- CSS Container Queries recipe — focused container-query patterns
- CSS Dark Mode recipe — pairing layouts with color-scheme support
- MDN: CSS Grid Layout — the definitive Grid reference
- MDN: Flexbox — Flexbox concepts and properties
- MDN: Container queries — syntax and containment context
Frequently Asked Questions
Should I use Grid or Flexbox for my layout?
Grid for two-dimensional layouts where rows and columns align together — page skeletons, card grids, dashboards. Flexbox for one-dimensional distribution — nav bars, button groups, card internals. Most pages use both: Grid for the skeleton, Flexbox inside components. If you're wrapping items and expecting rows to align, you wanted Grid.
What is subgrid and which browsers support it?
Subgrid lets a grid item inherit the parent grid's track definitions so nested content aligns with the outer grid — the classic fix for aligned card titles/prices. Supported in all modern browsers as of 2024 (Chrome 117+, Firefox 71+, Safari 16+). There's no polyfill for old browsers; use it for progressive enhancement.
How do container queries differ from media queries?
Media queries respond to viewport size; container queries respond to a parent element's size. A card using container queries adapts whether it sits in a sidebar or a hero — the component is self-contained and portable. Declare container-type: inline-size on the parent, then @container rules inside.
What are logical properties and why use them?
Logical properties (margin-inline, padding-block, text-align: start, inline-size) resolve against writing direction instead of physical sides. In LTR they behave like left/top; in RTL they flip automatically — one stylesheet serves both. Use them anywhere you'd otherwise reach for *-left/*-right physical properties.
What is the difference between flex: 1 and flex: auto?
flex: 1 expands to 1 1 0% — items share space equally regardless of content. flex: auto expands to 1 1 auto — items start from their content width and share only the leftover space. Equal columns? flex: 1. Content-aware sizing? flex: auto.
How do I create a responsive grid without media queries?
grid-template-columns: repeat(auto-fit, minmax(min(100%, 280px), 1fr)). auto-fit adds as many columns as fit, minmax bounds each between ~280px and 1fr, and min(100%, 280px) prevents overflow under 280px viewports. Choose auto-fit to stretch items into the row or auto-fill to keep consistent item sizes.
Related Resources
Complete Guide to Mobile Responsive Design
Build layouts that work on every screen. Mobile-first breakpoints, Grid, Flexbox, container queries, fluid type and responsive images.
RecipeWeb Performance Optimization
Improve Core Web Vitals, reduce bundle sizes, and optimize frontend performance with lazy loading, code splitting, and modern build tools.
GuideBundle Size Optimization: A Practical Frontend Guide
A hands-on guide to measuring and reducing JavaScript bundle size with tree shaking, code splitting, dependency swaps, compression, and CI budgets.
GuideWCAG 2.2 Accessibility: A Developer Guide
A practical guide to WCAG 2.2 compliance: the four POUR principles, ARIA, keyboard navigation, accessible forms and modals, tested with real code examples.
RecipeCSS Container Queries for Responsive Components
How to use CSS container queries so components adapt to the space they actually get inside a sidebar, grid cell, or card — not just the viewport width.
RecipeDark Mode with prefers-color-scheme and CSS Variables
How to implement dark mode using CSS prefers-color-scheme media query, CSS custom properties, and manual toggle with localStorage persistence.