The stacking order of elements in the document is determined based on the layout algorithm which is used.
- No overlap by default.
- Use negative margin to create overlap.
- Order of the elements matters. Elements coming later will be on top.
- Note: Content is painted separately from the background, so content from an earlier element will stack above the background of a later element.
Flow Layoutisn't really designed for layering.
- Positioned elements will typically render on top of non-positioned elements.
- Browser renders all non-positioned elements (i.e.
Flow Layout,Flex Layout,Grid Layout). - Browser renders all positioned elements (i.e.
relative,absolute,fixed,sticky).
- Browser renders all non-positioned elements (i.e.
- If two elements both have a
positionthen DOM ordering matters.
This property can be used to change the default browser layering.
- Only works with positioned elements or
Flex LayoutorGrid Layoutchildren. - No effect on elements rendered with
Flow Layout.- Note: works with
Flex LayoutandGrid Layout.
- Note: works with
- The default value is
autowhich is equivaent to0, so setting another element to any number higher will cause it to stack on top. - Can be set to a negative number, but this shouldn't be needed.
- Only compared with elements within a given stacking context. A stacking context can be created in the following ways:
- Setting the
positiontoabsoluteorrelativeand specifying az-index. - Setting the
positiontofixedorsticky(no need for az-index). - Setting
opacityto less than1. - Applying a
mix-blend-mode. - Setting
displaytoflexorgridand specifying az-index. - Using
transform,filter,clip-path,perspectiveormask. - Using
isolation: isolate;. This is a good way to create a stacking context without forcing random stacking with arbitraryz-indexvalues.
- Setting the
<div id="div-one" style="position: relative; z-index: 2;">
I'm above the second div
</div>
<div id="div-two" style="position: relative; z-index: 1;">
<p style="z-index: 100000;">
I am below "div-one" because my stacking
context "div-two" is below "div-one"
</p>
</div>Notes: