03. Sticky Headers, z-index & Stacking Contexts (isolation)
🟡 Intermediate
1. Definition
position: sticky acts as relative positioning until a scroll threshold is met, whereupon it sticks like fixed positioning within its parent. z-index controls 3D stacking order, and isolation: isolate creates an independent stacking context.
2. Why It Is Used
Sticky positioning keeps table headers and navigation bars visible during scrolling. Stacking contexts prevent z-index battles where child elements accidentally bleed over parent modals.
3. How It Works
Sticky elements remain in flow until top: 0 touches the viewport boundary. Stacking contexts create independent depth layers where z-index values are evaluated locally.
4. Syntax
.sticky-nav {
position: sticky;
top: 0;
z-index: 100;
}
.isolated-card {
isolation: isolate; /* Creates local stacking context */
}
5. Stacking Order Rules Table
| Stack Layer | Element Type | Default z-index |
|---|---|---|
| Layer 1 (Bottom) | Background & Borders | Auto |
| Layer 2 | Non-positioned block elements | Auto |
| Layer 3 | Positioned elements (relative, absolute, sticky) | Explicit z-index number |
| Layer 4 (Top) | Top-layer popovers & dialogs | Top Layer Context |
6. Beginner Example
.table-header {
position: sticky;
top: 0;
background-color: #f8fafc;
}
7. Intermediate Example
.dropdown-menu {
position: absolute;
top: 100%;
left: 0;
z-index: 50;
}
8. Advanced Stacking Context Isolation Example
/* Prevents child badge z-index 9999 from bleeding over global navbar */
.card-component {
position: relative;
isolation: isolate;
}
.card-badge {
position: absolute;
top: -10px;
right: -10px;
z-index: 10;
}
9. Line-by-Line Code Explanation
isolation: isolate;: Explicitly creates a new stacking context, capping internal z-index values inside.card-component.
10. Expected Terminal / Browser Output
Sticky table headers that remain pinned at screen top during table scrolling without overlapping global page navigation menus.
11. Common Mistakes & Pitfalls
- Forgetting
top: 0on sticky elements:position: stickydoes nothing unless an offset threshold (liketop: 0) is declared.
12. Important Rules & Limitations
- Sticky elements stop sticking when their parent container scrolls completely out of view.
13. Multilingual Explanation: English
sticky pins elements upon reaching a scroll threshold. isolation: isolate prevents z-index bleeding by establishing a local stacking context.
14. Multilingual Explanation: Hindi (Roman Script)
sticky scroll threshold aane par pin ho jata hai. isolation: isolate se local z-index stack banta hai.
15. Multilingual Explanation: Marathi (Roman Script)
sticky scroll hotaach pin hoto. isolation: isolate z-index conflicts thambvto.
16. Practice Questions
- Why does
position: stickystop sticking if an ancestor hasoverflow: hidden?
17. Practical Coding Challenge
Create a .sticky-header rule with position: sticky, top: 0, z-index: 100, and background: #ffffff.