Performance: Stacking context
Stacking context affects how elements are layered visually and can impact paint and composite performance during rendering.
Jump into concepts and practice - no test required
/* CSS */ .element { position: relative; z-index: 1; /* No opacity or transform here */ }
/* CSS */ .element { position: relative; z-index: 1; opacity: 0.99; transform: translateZ(0); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Many stacking contexts (opacity, transform) | No extra DOM nodes | 0 | High paint and composite cost due to multiple layers | [X] Bad |
| Minimal stacking contexts (only needed z-index) | No extra DOM nodes | 0 | Lower paint and composite cost with fewer layers | [OK] Good |
position: relative and z-index set mentions position: relative with z-index, which creates a stacking context. Other options do not create stacking contexts.position: relative and z-index set -> Option Bposition: relative and z-index: 5, which correctly creates a stacking context. Others either have static position or irrelevant properties.<div class='parent'>
<div class='child1'>Child 1</div>
<div class='child2'>Child 2</div>
</div>
.parent { position: relative; z-index: 1; }
.child1 { position: absolute; z-index: 2; }
.child2 { position: absolute; z-index: 1; }position: relative and z-index: 1, creating a stacking context. Children stack inside this context.z-index: 2, child 2 has z-index: 1. Higher z-index means it appears on top..box { position: absolute; }z-index is set.position: absolute but no z-index, so no stacking context is created.z-index property -> Option A<div class='outer'> <div class='inner'>Content</div> </div>
.outer { position: relative; z-index: 1; }
.inner { position: relative; z-index: 10; }position: relative and z-index: 1. The inner element creates a new stacking context inside outer with position: relative and z-index: 10.