Stacked Modals and Z-Index
What you'll learn: How to properly layer multiple modals on top of each other while maintaining focus management and visual hierarchy.
Sometimes a user action inside one modal triggers another modal to appear—like opening a "Delete Confirmation" dialog from a "Settings" modal. When this happens, you need to manage both the visual stacking order and keyboard focus carefully.
Understanding Z-Index Layering
The z-index CSS property controls the stacking order of positioned elements. Higher values appear on top. When modals stack, each subsequent modal needs a higher z-index than the previous one:
.modal-backdrop {
z-index: 1000;
}
.modal-content {
z-index: 1001;
}
.modal-backdrop.stacked {
z-index: 1100; /* Second backdrop above first modal */
}
.modal-content.stacked {
z-index: 1101; /* Second modal on top */
}
Focus Management Across Layers
When a second modal opens, focus must move to the new modal and be trapped there. The first modal's focus trap becomes temporarily inactive but preserves its state. Think of it like stacking plates—only the top plate is accessible.
When the top modal closes, focus must return to the element that triggered it in the first modal, and that modal's focus trap reactivates. You're essentially maintaining a stack: open second modal → push to stack, close second modal → pop from stack and restore.
Practical Considerations
Each modal needs its own backdrop to visually separate layers. The bottom modal should become slightly dimmed or visually de-emphasized when covered. Screen readers should only announce the currently active (top) modal.
Key Takeaway: Stacked modals require incrementing z-index values for proper visual layering and a focus management stack that activates only the topmost modal's focus trap while preserving return points for each layer.