You can see the issue in this fiddle.
I've got an absolutely positioned element with a z-index of 2 and a relatively positioned element with a z-index of 1. The relatively positioned element contains the absolutely positioned one. I thought that the z-index:2 element would show above the z-index:1 items, but it does not. Is there a way to fix this so that the z-index:2 items are above all z-index:1 items?
div {
background: green;
position: relative;
width: 100%;
z-index: 1;
}
span {
top: 0;
right: 0;
z-index: 2;
position: absolute;
border: solid 1px red;
height: 70px;
background: white;
}
<div>
Row 1
<span>I thought this would show above 'Row 2'</span>
</div>
<div>
Row 2
</div>
Clearly, nothing can be absolute and relative at the same time. Either you want the element to position itself based on another ancestor's position or based on the page flow.
An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed). However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.
Whenever you set position: absolute; to an element, it must be positioned relative to something. Your absolute element will look for the closest parent with position: relative; , and position itself relative to it. If there are no elements like that, it will be positioned relative to the body element.
Absolute An element with position: absolute is removed from the normal document flow. It is positioned automatically to the starting point (top-left corner) of its parent element. If it doesn't have any parent elements, then the initial document <html> will be its parent.
When you add a z-index
to a child that is in a positioned parent element that also has a z-index
, the parent z-index
starts a new stacking order, and the child z-index
is relative to the parent's z-index
. So in this case, z-index: 2
is only compared to other elements inside of the parent with z-index: 1
. To get around this, you could just apply the z-index
to the span
, or don't give the last div
a z-index
You can read more about it here https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context
body {
font-family: arial;
}
* {
padding: 10px;
}
div {
background: green;
position: relative;
width: 100%;
}
div:first-child {
z-index: 1;
}
span {
top: 0;
right: 0;
z-index: 2;
position: absolute;
border: solid 1px red;
height: 70px;
background: white;
display: inline-block;
}
<div>
Row 1
<span>
I thought this would show above 'Row 2'
</span>
</div>
<div>
Row 2
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With