I have two images on either side of a box. They’re both supposed to go behind the box, the left image is styled correctly, the right image isn’t. I can’t get the image to go behind the box and stay attached to the box like my left image. I’ve tried playing with the margins which causes the images to move when the viewport changes, which is not what I want.
How would I best get my right image to go behind my box?
<body>
<img id="leftimg" src="/Images/left.png">
<main>
</main>
<img id="rightimg" src="/Images/right.png">
</body>
main {
width: 33em;
height: 31em;
z-index: 999;
}
#leftimg {
z-index: 1;
width: auto;
margin-right: -1.5em;
height: 35em;
}
#rightimg {
z-index: 1;
width: auto;
margin-left: -2em;
height: 35em;
}
I put my right image after my box and before the body ends. This results with the image going on top of the box instead of behind it, despite the fact the z-index should (as far as I know) make it go behind it.
2
Answers
Your code seems to work just fine. All I had to do is wrap it into
<div>
that usesflexbox
.Also I would personally recommend to just crop the image – less waste of data, and easier layout.
TLDR: Adding
position: relative;
to your tags will allow the z-index to be properly applied.Regarding your particular issue, you are applying a
z-index
to tags (the images and the main tag) with noposition
value (which resolves tostatic
by default). With astatic
position, thez-index
value is ignored.As for why the left image is below and not the right image, that is due to the elements order in the DOM. Since the
z-index
is ignored, the elements stack above each other, the first being the lower in the stack.