Course contentsShow
← Web Development
Lesson 252 of 2,9824. CSS Layout FoundationsFree lesson

overflow patterns: sticky headers and modal scrolling

Implement common overflow patterns like body scroll locking and scrollable modal content.

Overflow Patterns: Sticky Headers and Modal Scrolling

You'll learn how to combine overflow and positioning to create sticky headers and prevent background scrolling behind modals.

When building real-world interfaces, you'll often need two specific overflow patterns: keeping a header visible while content scrolls beneath it, and locking the page's scroll when a modal dialog appears.

Sticky Headers with Scrollable Content

A sticky header stays fixed at the top while the main content scrolls. You combine position: sticky with a scrollable container:

.container {
  overflow-y: auto;
  height: 500px;
}

.header {
  position: sticky;
  top: 0;
  background-color: white;
  z-index: 10;
}

The header "sticks" to the top of its scrollable parent. Think of it like a bookmark that slides down but never leaves the visible area.

Modal Scroll Locking

When a modal opens, you typically want to prevent the page body from scrolling behind it. This prevents a jarring experience where users accidentally scroll the background content:

/* When modal is open, apply to body */
body.modal-open {
  overflow: hidden;
  height: 100%;
}

.modal-content {
  overflow-y: auto;
  max-height: 80vh;
}

By setting overflow: hidden on the body, you lock background scrolling. The modal itself uses overflow: auto so its content can scroll independently.

This creates a "scroll trap"—like closing the doors to one room before opening another, ensuring users only interact with one scrolling context at a time.

Key Takeaway: Use position: sticky with overflow: auto containers for sticky headers, and toggle overflow: hidden on the body to lock scrolling when modals appear—two essential patterns for professional web interfaces.