In CSS, "stacking context" is merely how a parent element and its descendants are treated as a group, such that the following things are done in isolation from elements outside the stacking context:
- Descendants are composited and blended with other elements within the same context;
z-index,opacity,transforms, and clipping/masking are calculated relative to the context they're in.
The default stacking context is the root element of the document (<html>). However, other HTML elements on the page can create their own stacking context when the following CSS properties are specified on them:
- Compositing and Blending Properties:
opacityvalue set to less than1;mix-blend-modeset to value other thannormal;transform,filter,backdrop-filter,perspective,clip-path,mask,mask-imageormask-borderset to value other thannone;isolationvalue set toisolate.
- Positioning Properties:
positionvalue set toabsoluteorrelative, havingz-indexvalue other thanauto;positionvalue set tofixedorsticky.
- Layout Properties:
- Child of a
flexorgridcontainer withz-indexvalue other thanauto.
- Child of a
- Performance Properties:
will-changevalue specifying any property that might change, directing the browser to create a new composite layer for that element;containvalue set tolayoutorpaint, or a composite value that includes either of them (i.e.contain: strict,contain: content).
For example:
<div id="parent-1"> <code>z-index: 1</code> <div id="child-1"><code>z-index: 3</code></div> </div> <div id="parent-2"> <code>z-index: 2</code> <div id="child-2"><code>z-index: auto</code></div> </div>
#parent-1 {
width: 300px;
height: 300px;
position: absolute;
z-index: 1;
background: aqua;
}
#child-1 {
position: relative;
z-index: 3;
background: yellow;
}
#parent-2 {
width: 200px;
height: 200px;
position: relative;
z-index: 2;
background: pink;
}
In this example, "child-1" is rendered behind "parent-2" even though it has a higher z-index value. This is because the z-index of all descendants of a parent that establishes a new stacking context, is relative to the parent's stacking order, which in this case, is positioned behind "parent-2". This means that elements with a higher z-index value are only positioned on top of elements with a lower z-index value within the same stacking context.
It's important to note that creating too many stacking contexts can negatively impact web page performance. Therefore, it's important to use them only when necessary.
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.