调整窗口大小时使重叠图像居中

时间:2018-09-28 04:40:28

标签: html css

我有2张相同大小的图像,需要完全重叠并在窗口调整大小时保持重叠。由于某种原因,设置位置:绝对;反转居中。 到目前为止,这里是代码,我已经用Google图片上的通用图片替换了我的图片。

<img src = "http://www.brittlestar.org.uk/wp-content/uploads/2014/02/300x300.gif" width = 50%  height = auto style="position: relative; margin-left: auto; margin-right: auto; display: block;">
<img src = "https://www.leadheroes.com/wp-content/uploads/superforms/2018/07/883153652/5361c9b53077aa52c50fa005b15c6c4f%20(2)-300x300.png" width = 50% height = auto style = "position: absolute; z-index: 2; top: 50%; margin-left: auto; margin-right: auto; display: block;">

有人知道如何解决此问题吗? 谢谢。

4 个答案:

答案 0 :(得分:0)

我希望这是你正在寻找的:)

注意:请花点时间阅读https://stackoverflow.com/help/how-to-ask,如果您不提供任何代码,此处的人将无法帮助您

html, body {
  height: 100%;
}
div {
  top: 50%;
  position: relative;
  margin-left: auto;
  margin-right: auto;
  width: 300px;
  transform: translateY(-50%);
}
img {
  max-width: 100%;
}
.overlap {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
}
<div>
  <img src="https://via.placeholder.com/300x300">
  <img class="overlap" src="https://www.leadheroes.com/wp-content/uploads/superforms/2018/07/883153652/5361c9b53077aa52c50fa005b15c6c4f%20(2)-300x300.png">
</div>

答案 1 :(得分:0)

您可以将一张图片保留为div背景,另一张保留为div的内容

HTML

.imageCont{background: url('http://www.brittlestar.org.uk/wp-content/uploads/2014/02/300x300.gif') center no-repeat; width:300px; height:300px;display:flex; align-items:center;justify-content: center;}
<div class="imageCont">
<img src ="https://via.placeholder.com/300x300"/>
</div>

让我知道这是否适合您。

答案 2 :(得分:0)

根据您提供的代码,您可以使用以下代码获得所需的输出。

<div>
    <img src="http://www.brittlestar.org.uk/wp-content/uploads/2014/02/300x300.gif" style="position: relative; margin-left: auto; margin-right: auto; display: block;">
    <img src="https://www.leadheroes.com/wp-content/uploads/superforms/2018/07/883153652/5361c9b53077aa52c50fa005b15c6c4f%20(2)-300x300.png" style="position: absolute;top: 0;left: calc(50% - 150px);">
</div>

答案 3 :(得分:0)

您必须使用包含两个图像的容器框,并将position: relative添加到该框。您也可以使用 flex 将框的内容居中。最后,向要重叠的图像添加position: absolute。这是一个示例:

.container {
  width: 50%;
  display: flex;
  position: relative;
  margin: 0 auto;
  align-items: center;
  justify-content: center;
}

.container img {
  width: 100%;
}

.container img.overlap {
  position: absolute;
}
<div class="container">
  <img src="https://dummyimage.com/300x300/c9c9c9/fff">
  <img class="overlap" src="https://www.leadheroes.com/wp-content/uploads/superforms/2018/07/883153652/5361c9b53077aa52c50fa005b15c6c4f%20(2)-300x300.png">
</div>