The z-index property controls which positioned elements appear in front when their boxes overlap. Larger integer values paint in front of smaller values; negative values can place elements behind static elements. section 6.4.1 section 6.4.2
Use z-index with these rules in mind:
- Apply it only to positioned elements; static elements cannot have their stacking order changed this way. section 6.4.2
- Treat every z-indexed positioned element as the root of a new stacking context containing all its descendants. section 6.4.2 section 6.4.3
- Compare stacking contexts before comparing descendants: a child with z-index 100 cannot escape its parent context and overtake an element in a higher context. section 6.4.3
Putting a modal body above its backdrop
A fixed modal can remain anywhere in the markup, but assigning the backdrop z-index 1 and the modal body z-index 2 makes the body paint in front. Both elements are positioned, so the values take effect. section 6.4.1 section 6.4.2
Listing 6.13 Creating the stacking contexts
body {
margin: 40px;
}
.box {
display: inline-block;
width: 200px;
line-height: 200px;
text-align: center;
border: 2px solid black;
background-color: #ea5;
margin-left: -60px;
vertical-align: top;
}
.one { margin-left: 0; }
.two { margin-top: 30px; }
.three { margin-top: 60px; }
.positioned { #1
position: relative; #1
background-color: #5ae; #1
z-index: 1; #1
} #1
.absolute {
position: absolute;
top: 1em;
right: 1em;
background-color: #fff;
border: 2px dashed #888;
z-index: 100; #2
line-height: initial;
padding: 1em;
}
Experiment with two overlapping positioned boxes and a nested absolute element. Although the nested element has z-index 100, its parent stacking context can remain behind the other box. section 6.4.3
--z-loading-indicator: 100; --z-nav-menu: 200; --z-dropdown-menu: 300; --z-modal-backdrop: 400; --z-modal-body: 410;
A named scale keeps interface layers understandable: loading indicator, navigation menu, dropdown, modal backdrop, and modal body receive progressively higher values. section 6.4.3

