如何将屏幕右侧的图像设置为位于<main>框后面?

问题描述 投票:0回答:1

我在盒子的两侧都有两个图像。它们都应该位于盒子后面,左侧图像的样式正确,右侧图像则不然。我无法让图像像左图一样进入盒子后面并保持附着在盒子上。我尝试过使用边距,这会导致图像在视口更改时移动,这不是我想要的。

我怎样才能最好地将正确的图像放在我的盒子后面?

<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.

我将右侧图像放在方框之后、正文结束之前。这导致图像位于框的顶部而不是后面,尽管 z-index 应该(据我所知)使其位于框的后面。

html css image z-index
1个回答
0
投票

您的代码似乎工作得很好。我所要做的就是将其包装到使用

<div>
flexbox
中。

我个人建议只裁剪图像 - 减少数据浪费,并且更容易布局。

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>

© www.soinside.com 2019 - 2024. All rights reserved.