How can I keep keyboard focus inside a modal dialog while it is open?
Quick answer
When a modal opens, move keyboard focus to a logical starting point inside it. While it remains open, Tab and Shift+Tab should cycle through its usable controls rather than moving to the page behind it. When it closes, return focus to the element that opened it, if that element still exists and is usable. Test these behaviors with a keyboard; a visual overlay alone does not establish them.
The question, the details, the next step.
A practical checklist
Name the element that receives focus when the dialog opens, and record why it is the logical starting point.
Use Tab and Shift+Tab to verify focus cycles through the dialog’s usable controls.
Check that keyboard focus does not reach the page behind the open modal.
Close the dialog and verify focus returns to its opener when that control remains usable.
Test and document a meaningful fallback if the opener is unavailable.
A few more useful answers
Should initial focus always go to the first button?
No. Choose a starting point that fits the dialog’s task and content. The cited WinUI guidance discusses a logical first or primary action, but it is Windows-app guidance rather than a universal web-dialog rule. [S2]
Does a dark overlay keep keyboard focus inside a modal?
Not by itself. Check the actual keyboard behavior: Tab and Shift+Tab should stay within the open modal rather than reaching the background. Fluent UI documents that behavior for its modal component. [S1]
Sources
References used for this guide.
- [S1] Dialog — Microsoft Fluent UI Web Components learn.microsoft.com · Checked
- [S2] Keyboard interactions — Windows apps learn.microsoft.com · Checked
