问题
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:
http://jsfiddle.net/n2Kq5/
http://jsfiddle.net/U8Jem/1/
回答1:
In short, yes, an element with position:fixed
is limited by its parent's z-index given the parent's z-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 of outer
, which would look like this.
The second option for an HTML fix is to move fade
inside of outer
(using the same CSS even) - demo of that here.
A third option would be to put fade
inside of outer
and then also put inner
inside of fade
, 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
and outer
are on the same level. What you're trying to do is have fade
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.
来源:https://stackoverflow.com/questions/19841997/is-position-fixed-z-index-relative-to-its-parents-z-index