为什么我的div隐藏在position:absolute images之后?

时间:2019-05-07 19:08:46

标签: html css

在此代码中,我使用绝对定位将两个图像彼此重叠,但是类row的第二个div似乎隐藏在图像后面。如何解决该问题并将其显示在正确的位置(在图像之后)?

.composition {
  position: relative;
}

.img-1 {
  position: absolute;
  top: 0;
  left: 0;
}

.img-2 {
  position: absolute;
  top: 0;
  left: 0;
}
<div class="row">
    <div class="composition">
        <img src="imgs/lenses.jpg" class="img-fluid img-1" alt="" />
        <img src="imgs/mountain-1.jpg" class="img-fluid img-2" alt="" />
    </div>
</div>

<div class="row">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita praesentium inventore iusto rem perspiciatis impedit.
</div>

2 个答案:

答案 0 :(得分:0)

如前所述,图像上的绝对位置导致.composition不具有高度,并且其下面的div在图像下塌陷。

为什么两个图像都需要绝对定位?保留一幅没有绝对位置的图像,以便.composition具有图像的高度。可以完全定位第二个图像以覆盖第一个图像。

在第一个图像停留在流中并保持高度的情况下,第二个div将保持在图像下方。

.composition {
  position: relative;
}

.img-2 {
  position: absolute;
  top: 0;
  left: 0;
}
<body>
    <div class="row">
    <div class="composition">
        <img src="https://picsum.photos/id/237/100/100" class="img-fluid img-1" alt="">
        <img src="https://picsum.photos/id/1021/100/100" class="img-fluid img-2" alt="">
    </div>
</div>

<div class="row">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita praesentium inventore iusto rem perspiciatis impedit.
</div>

答案 1 :(得分:-1)

只需将图像的位置:绝对更改为位置:相对。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<style type="text/css">
    .composition {
        position: relative;
    }
    .img-1 {
        position: relative;
        top: 0;
        left: 0;
        width: 100px; 
        height: 150px;
    }
    .img-2 {
        position: relative;
        top: 0;
        left: 0;
        width: 100px;
        height: 150px;
    } 
</style>
<body>
    <div class="row">
        <div class="composition">
            <img src="https://i.ebayimg.com/images/g/lAgAAOSwWAhcFLHg/s-l300.jpg" class="img-fluid img-1" alt="" />
            <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS1bHL-HroyjayQ-OzEENg90I7a6CdtNRnn6l7KdSC8LlXr7H5w" class="img-fluid img-2" alt="" />
        </div>
    </div>
    <div class="row">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita praesentium inventore iusto rem perspiciatis impedit.
    </div>
</body>
</html>