The CSS z-index
behaves differently for both, the grid layout and the grid items within it:
- Grid Layout: The
z-index
property does not directly apply to the grid layout itself. To applyz-index
to a grid container, you must set theposition
property to a value other thanstatic
. - Grid Items: The
z-index
property can be applied directly on grid items — i.e. direct children ofdisplay: grid
ordisplay: inline-grid
element. This allows you to control the stacking order of individual grid items, determining which items appear in front of or behind others within the same grid 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 grid 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: grid; grid-template-columns: 1fr 1fr; width: 150px; height: 150px; padding: 1em; border: 1px solid red; } #child-1 { grid-column: 1; z-index: 3; background: aliceblue; border: 2px solid lightblue; } #child-2 { grid-column: 1 / span 2; margin-top: -10px; z-index: 1; background: pink; border: 2px solid hotpink; } #child-3 { grid-column: 2; margin-top: -10px; z-index: 2; background: wheat; border: 2px solid gold; }
By applying negative margin-top
on second and third elements, you can see how the grid items with the higher z-index
appear in front of grid 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 grid items appear in front of the second grid item as they have a higher z-index
.
Please note that when a grid 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 grid 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.