如何使用 z-index 制作重叠图像的场景并保持设计的响应性?

How can I make a scene of overlapping images with z-index and keep the design responsive?

我是一名插画师,正在为网络创作作品,并且对 HTML、CSS 和 Javascript 相当陌生。对于我的基本场景,我需要一张鸟的图像来重叠天空的图像,因为在最终版本中我将简单地为这只鸟制作动画(拍打翅膀等)。

我制作了一个 div,其中包含山的图像和鸟的图像。使用 CSS,我已经成功地将它们与 z-index 重叠,但我似乎无法根据它们之间的关系获得相对百分比值(即我需要在某个地方的鸟天空)。我还查找了一种使整个设计响应的方法,该方法使用一个标签来控制视口,但即使在包含它之后也无法缩放。如果有任何帮助,我将不胜感激——我正在努力思考定位问题,但我尝试的任何方法都不起作用。

HTML

<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  </head>

  <body>

    <div id='scene'>
        <img class='sky' src='skybox.png'>
        <img class='bird' src='bird.png'>
    </div>

  </body>

</html>

CSS

#scene {
    position: relative;
    z-index: -1;
}

.sky {
    position: relative;
    z-index: 1;
}

.bird{
    position: relative;
    z-index: 2;
    /* this is where I'd like to add some percentage that 
    would be responsive and also put the bird at a certain 
    place in the sky. Pixel values work to position it but 
    the top has to be negative even to get it in the sky at 
    all, and percentages do nothing */

}

您想将父容器放入 position: relative,然后将子容器放入 position: absolute 这样,您就可以控制它们在 父容器中的行为方式div。

如果您使用的图片尺寸相同,很多 会更容易。如果是,您只需像这样设置页边距:

.bird, .sky, .sun {
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

这里有一个片段供您学习。 :) 如果您有任何问题,请告诉我!

.scene {
  position: relative;
  width: 50vw;
  height: 50vh;
  z-index: 0;
  overflow: hidden;
}

.bird, .sky, .sun {
  position: absolute;
}

.bird {
  border: 1px solid red;
  height: 10%;
  width: 5%;
  bottom: 10%;
  left: 20%;
  background-color: red;
  z-index: 1;
  overflow: hidden;
}

.sky {
  width: 100%;
  height: 100%;
  background-color: lightblue;
}

.sun {
  top: -10%;
  right: -10%;
  height: 30%;
  width: 20%;
  border-radius: 100%;
  background-color: yellow;
  z-index: 2;
  overflow: hidden;
}
<div class="scene">
  <div class="bird"></div>
  <div class="sky"></div>
  <div class="sun"></div>
</div>