如何在div内居中放置2张图像

时间:2020-11-10 14:26:54

标签: html css

我有一个要填充浏览器窗口宽度的div。

在div内,我想要2张图像,彼此重叠,每个图像都位于div的中心。图像可以是任何尺寸。两张图片都需要保持其长宽比,我不希望它们中的任何一个作为div的背景。

  .parent {
    position: relative;
    border: 1px solid blue;
    width: 100%;
  }
  .child {
    border: 1px solid red;
    margin-left: auto;
      margin-right: auto;
      display: block;
    max-width: 100%;
  }
  .ontop{
    z-index:1;
  }
  <div class="parent">
    <img class='child ontop' src="https://i.postimg.cc/yNh7V4v1/spaceship.png">
    <img class='child' src="https://i.postimg.cc/mgB04zzn/universe.jpg">
  </div>

fiddle

这里的问题是它们不在彼此之上。我可以使它们彼此重叠,并至少在水平方向居中

  .parent {
    position: relative;
    border: 1px solid blue;
    width: 100%;
  }
  .child {
    position: absolute;
    border: 1px solid red;
    margin-left: auto;
      margin-right: auto;
      display: block;
    max-width: 100%;
    left: 50%;
    transform: translate(-50%);
  }
  .ontop{
    z-index:1;
  }
  <div class="parent">
    <img class='child ontop' src="https://i.postimg.cc/yNh7V4v1/spaceship.png">
    <img class='child' src="https://i.postimg.cc/mgB04zzn/universe.jpg">
  </div>

fiddle

但是现在的问题是,由于我使用绝对定位,因此图像不再包含在div中。

谁能告诉我该技术是什么?

2 个答案:

答案 0 :(得分:0)

使用position:absolute;将太空飞船放置在父级的中间位置。这要求父级与图像的宽度相同。我在示例中使用width: fit-content;

使用此方法,您可以将这三个HTML元素放入一个您可以移动的容器中,从而将图像集放置在任何位置。

.parent {
  width: fit-content;
  border: 1px solid blue;
  position: relative;
}

.parent img {
  border: 1px solid red;
}

.center {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
<div class="parent">
  <img class="center" src="https://i.postimg.cc/yNh7V4v1/spaceship.png">
  <img src="https://i.postimg.cc/mgB04zzn/universe.jpg">
</div>

是否要放大背景图像,只需更改其大小?在此示例中,我将其宽度设置为width: 100vw; 100视图宽度

(尽管您可能应该为所需的尺寸制定CSS规则,但在此示例中,我将其作为内联样式放置)

.parent {
  width: fit-content;
  border: 1px solid blue;
  position: relative;
}

.parent img {
  border: 1px solid red;
}

.center {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
<div class="parent">
  <img class="center" src="https://i.postimg.cc/yNh7V4v1/spaceship.png">
  <img style="width:100vw;" src="https://i.postimg.cc/mgB04zzn/universe.jpg">
</div>

答案 1 :(得分:0)

我建议您将图像(空间)移动到CSS背景图像。当您要将图像作为背景时,这是正确的方法。

将flex应用于父对象,您就很好了。

.parent {
 background-image: url(https://i.postimg.cc/mgB04zzn/universe.jpg);
    background-repeat: no-repeat;
    background-size: cover;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
}

.child{
      height: 100px;
    width: 100px;
}
 <div class="parent">
  <img class='child' src="https://i.postimg.cc/yNh7V4v1/spaceship.png">
 </div>