Alex
Alex

Reputation: 193

Why element with z-index 0 is shown above element with z-index 1

I have following code (example):

<div style="position: fixed">
  <div id="AAA" style="position: absolute; background-color: green; z-index: 1">AAA</div>
</div>
<div style="position: relative">
  <div id="BBB" style="position: absolute; background-color: red; z-index: 0">BBB</div>
</div>

For me it looks like AAA div should be shown over BBB div, because:

But in result HTML, BBB is shown over AAA. Why? Are there any document describing this behavior?

Upvotes: 2

Views: 1300

Answers (1)

Michael Coker
Michael Coker

Reputation: 53709

Because a position and z-index on the parent starts a new stacking order. Specifically position: fixed on the first element. https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context

A stacking context is formed, anywhere in the document, by any element in the following scenarios:

...

Element with a position value "fixed" or "sticky" (sticky for all mobile browsers, but not older desktop).

So the child z-index of the first div is relative to the parent, not the rest of the document.

In this example, you want to apply z-index to the parent instead.

<div style="position: fixed; z-index: 1;">
  <div id="AAA" style="position: absolute; background-color: green; z-index: 1">AAA</div>
</div>
<div style="position: relative;">
  <div id="BBB" style="position: absolute; background-color: red; z-index: 0">BBB</div>
</div>

Upvotes: 3

Related Questions