The CSS z-index
behaves differently for both, the flex layout and the flex items within it:
- Flex Layout: The
z-index
property does not directly apply to the flex layout itself. To applyz-index
to a flex container, you must set theposition
property to a value other thanstatic
. - Flex Items: The
z-index
property can be applied directly on flex items — i.e. direct children ofdisplay: flex
ordisplay: inline-flex
element. This allows you to control the stacking order of individual flex items, determining which items appear in front of or behind others within the same flex container when they overlap (due to negative margins or positioning for example).
For example, consider the following HTML/CSS which demonstrates how the z-index
property directly applies to flex items when they overlap because of negative margins:
<div id="parent"> <div id="child-1"><code>z-index: 3;</code></div> <div id="child-2"><code>z-index: 1;</code></div> <div id="child-3"><code>z-index: 2;</code></div> </div>
#parent { display: flex; flex-direction: column; width: 150px; height: 150px; padding: 1em; border: 1px solid red; } #child-1 { height: 50px; z-index: 3; background: aliceblue; border: 2px solid lightblue; } #child-2 { height: 50px; margin-top: -15px; z-index: 1; background: pink; border: 2px solid hotpink; } #child-3 { height: 50px; margin-top: -15px; z-index: 2; background: wheat; border: 2px solid gold; }
By applying negative margin-top
on second and third elements, you can see how the flex items with the higher z-index
appear in front of flex items with a lower z-index
, producing an output like the following:
z-index: 3;
z-index: 1;
z-index: 2;
As you can see in the example above, the first and third flex items appear in front of the second flex item as they have a higher z-index
.
Please note that when a flex item has a z-index
value other than auto
applied to it (even if its position
is set to static
), it creates a new stacking context. In such case, the descendants of flex items that are positioned outside it also participate in the stacking context it establishes.
This post was published 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.