A modal needs to stay in view while the page scrolls. Set position: fixed on its backdrop and dialog body to place them relative to the viewport rather than in normal document flow. section 6.1 section 6.1.1 section 6.0
Choose offsets according to the space the element should occupy:
- Use top, right, bottom, and left to set distances from viewport edges. Setting both left and right also determines the available width. section 6.1
- Use inset: 0 to reach all four edges. For separate vertical and horizontal distances, use inset-block and inset-inline. section 6.1 section 6.1.1
Backdrop and dialog
Give the backdrop position: fixed; inset: 0; to cover the viewport, then add a semitransparent background. Give the dialog body position: fixed; inset-block: 3em; inset-inline: 20%; and overflow: auto. The offsets leave space around the dialog, while overflow lets its contents scroll when needed. Toggle the surrounding modal between display: none and display: block to show it. section 6.1.1
Listing 6.3 Adding modal styles
.modal-backdrop {
position: fixed; #1
inset: 0; #1
background-color: rgb(0 0 0 / 0.5); #1
}
.modal-body {
position: fixed; #2
inset-block: 3em; #2
inset-inline: 20%; #2
padding: 2em 3em;
background-color: white;
overflow: auto;
}
Compare the full-viewport backdrop with the inset dialog body; both use fixed positioning but occupy different parts of the viewport. section 6.1.1
Fixed positioning also works for navigation that should remain visible during scrolling. One responsive layout keeps links in a horizontal flex row on small viewports, then fixes the menu to the left edge at wider widths. This is a different choice from sticky positioning, which keeps an element on screen while containing it within its parent. section 16.2 section 6.6
Viewport placement does not settle which overlapping element appears on top. Positioned elements appear ahead of static content, but their order relative to one another can still depend on markup order. If a dropdown covers a modal, check that order or control stacking with z-index. section 6.4.1

