I discovered a strange problem, when I render a page with an element that has a negative z-index (z-index: -1
) and call document.elementsFromPoint
, the result is that visually the element with the negative z-index
appears above the body but elementsFromPoint
places the element between the <html>
and <body>
elements.
<html>
<head></head>
<body>
<main>
<h1>A title</h1>
</main>
<img src="foo.bar" alt="foo bar">
</body>
</html>
If I apply CSS to move the image on top of the heading like this:
body {
background-color: #FFF;
}
img {
position: absolute;
}
Then the stack that I will get under the <h1>
from elementsFromPoint
will be:
<img>
<h1>
<main>
<body>
<html>
Now if I modify that CSS to make the image fall under the heading:
body {
background-color: #FFF;
}
img {
position: absolute;
z-index: -1;
}
Then visually, the image appear below the heading but still appears above the <body>
. However calling elementsFromPoint
I now get:
<h1>
<main>
<body>
<img>
<html>
Notice that the <img>
element is between the <body>
and <html>
elements. This makes sense because the <body>
will have a default z-index
of 0
, so the <img>
element should be rendered beneath it.
But if that's the case, why is the browser rendering the image above the <body>
? I have checked this in both Chrome and Firefox and the results are the same.
Edit: Here is a demonstration of this weird effect. The bread slices are both content from the <body>
tag, the other two images are sandwiched in between.
body {
background-image: url('https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/microsoft/209/bread_1f35e.png');
background-repeat: no-repeat;
font-size: 110px;
padding: 0.25em;
}
img {
position: absolute;
left: 10px;
top: 10px;
z-index: -1;
}
img + img {
top: 25px;
left: 25px;
}
<img src="https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/microsoft/209/herb_1f33f.png" alt="greens in the sandwich">
<img src="https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/microsoft/209/bacon_1f953.png" alt="meat between the bread">