I've recently discovered that when setting z-index:-1
to non-statically positioned elements, it can affect their hovering capabilities. Interestingly, the behavior of absolutely and fixed positioned elements varies under different conditions.
Absolutely/Fixed positioned elements lose the ability to hover partially only if there is text written after them. Hovering near the top border doesn't work in this case. However, if there is no text after them, hovering works correctly.
Relatively positioned elements completely lose their hovering capability, even without any text following them.
Relatively positioned:
<!DOCTYPE html>
<html>
<style>
.tooltip {
position: relative;
display: block;
border: 5px solid black;
padding: 5px;
z-index: -1;
}
.tooltip:hover {
color:red; background-color: yellow;
}
</style>
<body style="text-align:center;">
<p>Move the mouse over the text below:</p>
<div class="tooltip">
Hover over me
</div>
</body>
</html>
Absolutely positioned with text after it:
<!DOCTYPE html>
<html>
<style>
.tooltip {
position: absolute;
display: block;
border: 5px solid black;
padding: 5px;
z-index: -1;
}
.tooltip:hover {
color:red; background-color: yellow;
}
</style>
<body style="text-align:center;">
<p>Move the mouse over the text below:</p>
<div class="tooltip">
Hover over me
</div>
Random text
</body>
</html>
Fixed positioned with text after it:
<!DOCTYPE html>
<html>
<style>
.tooltip {
position: fixed;
display: block;
border: 5px solid black;
padding: 5px;
z-index: -1;
}
.tooltip:hover {
color:red; background-color: yellow;
}
</style>
<body style="text-align:center;">
<p>Move the mouse over the text below:</p>
<div class="tooltip">
Hover over me
</div>
Random text
</body>
</html>
Question: What is the reason behind the removal of hovering capabilities for absolutely/fixed positioned elements when setting z-index:-1, especially when there is text after them, while relative positioned elements lose their hovering capability entirely?
Addendum: Despite gaining some understanding from other users' help, I still have some lingering doubts:
Why does the entire viewport take on the color of the body? Even though the border indicates that the body doesn't cover the entire viewport, giving the body a color results in the whole viewport adopting that color.
If we hover over the inner child box with
z-index:-1
, why does the parent container (i.e., body) get automatically hovered as well?