I have a fixed position element inside a relatively positioned element, as far as I'm concerned the position: relative
element shouldn't have any effect on the position: fixed
(fixed elements are positioned relative to the window, right?).
However, the fixed elements z-index seems to be inherited by it's parent, to the point where it's z-index can be no higher than its parent's z-index.
I hope I'm making sense? Below is a HTML example of what I'm talking about:
.outer {
position: relative;
z-index: 2;
}
.inner {
background: #fff;
left: 50px;
position: fixed;
top: 40px;
z-index: 1000000;
}
.fade {
background: #555;
bottom: 0;
left: 0;
opacity: 0.5;
position: fixed;
right: 0;
top: 0;
z-index: 3;
}
<div class="outer">
<div class="inner">testing testing</div>
</div>
<div class="fade"></div>
If you change the following:
.outer { position: relative; z-index: 4; }
Then the .inner
element appears in front of the fade element.
I find this behaviour very peculiar... is there a way of working around this without moving the .inner
div, or changing the CSS of the .outer
div?
Fiddles of above code samples:
In short, yes, an element with
position:fixed
is limited by its parent's z-index given the parent'sz-index
is defined.Sad to inform you, but what you want is not currently possible. The only way you can get the effect you desire is to change your HTML or remove the z-index from
outer
.Changing HTML options
The first option is to move
inner
outside ofouter
, which would look like this.The second option for an HTML fix is to move
fade
inside ofouter
(using the same CSS even) - demo of that here.A third option would be to put
fade
inside ofouter
and then also putinner
inside offade
, but that requires you to use rgba colors and opacity - that demo is found here.Changing CSS options
The closest thing you can get using the same HTML you have currently is to remove the z-index of
outer
- Demo here. You would think that you could simply increment each element's z-index by two, but that does not work due to the fact that children elements cannot have a higher z-index than their parents (if the parent's z-index is set).Explanation
If you think about it,
fade
andouter
are on the same level. What you're trying to do is havefade
remain on that same level but also have it be on the level above, which is impossible. It's like trying to be on two floors of a building at once, it can't be done.Although what you need is not directly related to this article, Philip Walton created a great post on z-indexes and the effect opacity has on them, which could be useful to others looking at this question.