In CSS 2.1, z-index
only applies to positioned elements, and specifies two different things:
- The stack level of the box in the current stacking context.
- Whether the box establishes a stacking context.
But Flexbox says this:
Flex items paint exactly the same as inline blocks [CSS21], except that
order
-modified document order is used in place of raw document order, andz-index
values other thanauto
create a stacking context even ifposition
isstatic
.
Then, unlike CSS2.1, setting z-index
to some integer on a non-positioned flex item creates a stacking context.
However, I don't see defined anywhere which should be the stack level of this stacking context.
A similar case is opacity
, which can also create establish stacking contexts on non-positioned elements. But in this case the stack level is properly specified to be 0:
If an element with opacity less than 1 is not positioned, implementations must paint the layer it creates, within its parent stacking context, at the same stacking order that would be used if it were a positioned element with
z-index: 0
andopacity: 1
.
In my opinion these options are reasonable:
- The stack level is the value specified in
z-index
- The stack level is 0
- The flex item wraps its descendants in a stacking context so that they are painted together, but the flex item itself is painted as a normal in-flow non-positioned elements (as if it didn't establish an stacking context).
According to the following test, both Firefox and Chrome do the first option.
.container {
display: flex;
padding-left: 20px;
}
.item {
padding: 20px;
background: #ffa;
align-self: flex-start;
margin-left: -20px;
}
.item:nth-child(even) {
background: #aff;
margin-top: 40px;
}
.za::after{ content: 'z-index: auto'; }
.z0 { z-index: 0; } .z0::after{ content: 'z-index: 0'; }
.z1 { z-index: 1; } .z1::after{ content: 'z-index: 1'; }
.z-1 { z-index: -1; } .z-1::after{ content: 'z-index: -1'; }
<div class="container">
<div class="item z1"></div>
<div class="item z0"></div>
<div class="item za"></div>
<div class="item za"></div>
<div class="item z-1"></div>
</div>
Is this behavior defined somewhere?
CSS Working Group:
More information:
Also, although not a direct answer to the question, the following W3C Editor's Drafts provide strong hints as to where CSS is going with
z-index
and stacking contexts.11. Layered presentation ~ CSS Positioned Layout Module Level 3
12. Detailed stacking context ~ CSS Positioned Layout Module Level 3
4.3. Z-axis Ordering: the
z-index
property ~ CSS Grid Layout Module Level 1It's interesting to note that
z-index
, as currently defined in the CSS Positioned 3 Editor's Draft, applies only to positioned elements. This is no different than CSS 2.1. Yet grid items and flex items can both create stacking contexts withz-index
, even whenposition
isstatic
.