skip to Main Content

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;
  }

Picture of a box with two characters on side. Left character is behind the box, while the right character is on top of it.

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


  1. Your code seems to work just fine. All I had to do is wrap it into <div> that uses flexbox.

    Also I would personally recommend to just crop the image – less waste of data, and easier layout.

    main {
      width: 33em;
      height: 31em;
      z-index: 999;
      background: green;
    }
    
    #leftimg {
      z-index: 1;
      width: 3em;
      margin-right: -1.5em;
      height: 35em;
      background: red;
    }
    
    #rightimg {
      z-index: 1;
      width: 3em;
      margin-left: -2em;
      height: 35em;
      background: blue;
    }
    <div style="display: flex">
      <img id="leftimg" src="/Images/left.png">
      <main>
      </main>
      <img id="rightimg" src="/Images/right.png">
    </div>
    Login or Signup to reply.
  2. 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 no position value (which resolves to static by default). With a static position, the z-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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search