CSS Layout

Flexbox and Grid for responsive layouts, alignment, gaps, and named grid areas.

Introduction to CSS Layout

What You'll Learn

Modern layouts use Flexbox for one-dimensional alignment (rows or columns) and CSS Grid for two-dimensional areas. This page walks through both with responsive patterns you can reuse in dashboards, marketing sites, and apps.

  • When to choose flex vs grid (and when to combine them)
  • Common alignment, gap, and wrapping patterns
  • Responsive breakpoints without brittle pixel hacks
  • Sticky headers, holy-grail layouts, and card grids

Layout is where CSS earns its keep: turning a linear document into structured UI. Browsers now have excellent support for flex and grid; floats are legacy for page layout except niche cases.

Normal Flow, Flexbox, and Grid

Theory: In normal flow, block elements stack vertically and inline elements wrap horizontally. display: flex and display: grid create formatting contexts with new alignment and sizing rules.

ToolBest forThink of it as
Block / inline flowArticles, paragraphs, simple stacksDefault reading order
FlexboxToolbars, nav rows, vertically centering, distributing space in one axisOne-dimensional layout
GridPage templates, dashboards, card areas with rows and columnsTwo-dimensional layout

Flexbox: Alignment, Gap, and Wrapping

Theory: Set display: flex on the container. Children become flex items. Use justify-content for main-axis distribution, align-items for cross-axis alignment, and gap for spacing without margin hacks.

Step 1: Pick direction with flex-direction: row | column. Step 2: Allow wrapping with flex-wrap: wrap when items should move to the next line. Step 3: Size items with flex: 1 1 240px (grow, shrink, basis).

Example: Responsive card row
.cards {
    display: flex;
    flex-wrap: wrap;
    gap: 1rem;
}

.card {
    flex: 1 1 260px;
    min-width: 0; /* allows shrinking inside flex without overflow */
    padding: 1rem;
    border-radius: 12px;
    background: #fff;
    box-shadow: 0 4px 16px rgba(15, 23, 42, 0.08);
}
Sample output: Cards fill the row and wrap when space runs out; each card stays at least ~260px wide until the viewport forces a new row.

Centering with Flexbox

Theory: Centering a single element in a viewport or card is a classic flex pattern: justify-content: center + align-items: center on a container with defined height.

Example: Hero or empty state
.hero {
    min-height: 40vh;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    padding: 2rem;
}
Sample output: Content sits visually centered both horizontally and vertically within the hero area.

CSS Grid: Tracks, Gaps, and Areas

Theory: Grid defines rows and columns on a container. Items are placed into cells; you can use line numbers, span, or named grid-template-areas for readable layout code.

Example: Three-column responsive grid
.grid {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 1rem;
}

@media (max-width: 900px) {
    .grid { grid-template-columns: 1fr 1fr; }
}
@media (max-width: 600px) {
    .grid { grid-template-columns: 1fr; }
}
Sample output: Desktop shows three equal columns; tablet two; phone one—without changing HTML.

Named Grid Areas (Holy Grail)

Theory: grid-template-areas lets you sketch the page as ASCII art: header, sidebar, main, footer. Reorder areas in a media query for mobile.

Example: App shell
.app {
    display: grid;
    min-height: 100vh;
    grid-template-columns: 240px 1fr;
    grid-template-rows: auto 1fr auto;
    grid-template-areas:
        "header header"
        "sidebar main"
        "footer footer";
    gap: 0 1rem;
}

.app-header { grid-area: header; }
.app-sidebar { grid-area: sidebar; }
.app-main { grid-area: main; min-width: 0; }
.app-footer { grid-area: footer; }

@media (max-width: 768px) {
    .app {
        grid-template-columns: 1fr;
        grid-template-areas:
            "header"
            "main"
            "sidebar"
            "footer";
    }
}
Sample output: A classic sidebar layout on desktop; on small screens the sidebar drops below main content for a single-column flow.

Sticky Headers and minmax

Theory: position: sticky keeps a header or column visible while scrolling, within its containing block. Combine with minmax(0, 1fr) to prevent grid blowout from long words or wide tables.

Example: Sticky table header row (simplified)
.table-wrap { overflow: auto; max-height: 60vh; }
thead th {
    position: sticky;
    top: 0;
    background: #f8fafc;
    z-index: 1;
}
Sample output: Body rows scroll while column titles stay visible—better UX for long data tables.

Summary & Quick Reference

  • Use flex for toolbars, equal-height columns in a row, and vertical centering.
  • Use grid for full-page templates and irregular cell spans.
  • Prefer gap over margins for spacing between items.
  • Always set min-width: 0 on flex/grid children that contain text or tables to avoid overflow bugs.

Next steps: Practice rebuilding a simple dashboard: header + sidebar + scrollable main using grid areas, then swap to a single column under 768px.

Layout MCQ Test

Practice layout concepts with 15 interview-style multiple choice questions.

Score: 0/15

Layout Interview Questions

Prepare for layout interviews by focusing on structure, practical usage, and maintainable styling patterns.

Basic Interview Q&A

  1. What is Layout in CSS?Layout focuses on structured, readable styling patterns that scale in real projects.
  2. Why is structure important?Good structure reduces bugs, improves collaboration, and makes updates easier.
  3. How do selectors affect structure?Selector strategy controls reusability and override complexity.
  4. What is maintainable CSS?Maintainable CSS is modular, readable, and easy to extend without regressions.
  5. When should you split files?Split when features/components grow, so each file has a clear responsibility.
  6. How does naming improve clarity?Consistent naming makes components predictable and easier to debug.
  7. What is cascade awareness?Understanding cascade helps you avoid accidental overrides and style leaks.
  8. Why avoid over-specific selectors?Over-specific selectors are hard to override and increase maintenance cost.
  9. How do utility classes help?Utilities provide quick, reusable single-purpose styles.
  10. What is a good interview answer style?Give a clear definition first, then one practical implementation example.

Advanced Interview Q&A

  1. How do cascade layers improve architecture?@layer defines priority explicitly, reducing conflicts across modules.
  2. How do container queries help component design?They make components responsive to their parent size, not only viewport size.
  3. What causes specificity debt?Chained selectors and frequent overrides create brittle style systems.
  4. How do you optimize CSS delivery?Minify, remove unused styles, and inline critical CSS where useful.
  5. How do design tokens scale teams?Tokens enforce consistency and simplify theme updates across products.
  6. When is utility-first strategy appropriate?It works well when rapid UI composition and consistency are priorities.
  7. How do you benchmark CSS performance?Audit render cost, style recalculations, and layout shifts with DevTools.
  8. How do you refactor legacy CSS safely?Refactor in slices, add visual regression checks, and remove dead rules gradually.
  9. What are paint-friendly transitions?Prefer transform/opacity over layout-triggering properties for smooth animation.
  10. How do you maintain accessibility while styling?Preserve focus visibility, contrast, semantic intent, and non-color indicators.

Related Learning Links

Interview tip: explain concepts with one real codebase example for stronger answers.