CSS - 防止高度未知的相对 div 与下面的 div 重叠

CSS - prevent relative div with unknown height from overlapping the div below

<div id="container">
    <div id="div1">
        <img src="https://i.pinimg.com/originals/81/d2/bf/81d2bffd2d12c8275ab2c708b3fd5297.gif" id="image">
    </div>

    <div id="div2">

    </div>
</div>

CSS:

#container{
    width: 500px; 
    height: 500px;
    background-color: aquamarine;
}

#div1{
    display: block;
    position: relative;
    width: 100px;
    margin-bottom: 8px;
    background-color: burlywood;
}

#div2{
    display: block;
    width: 100%;
    height: 100px;
    background-color: red;
}

#image{
    width: 90px; 
    position: absolute;
    margin-right: 10px;
    margin-top: 10px;
}

当我指定 div1 的高度时,它会保持在上方但高度未知,因为我会动态地在其中添加一个高度也未知的图像。

有没有办法防止未知高度的 div1div2 重叠并保持在它上面?

我也试过把<div style="clear: both;"></div>放在他们中间

我复制了你的造型。我刚刚添加了一个min-height。和一个 image-container.

document.getElementById("show-hide").addEventListener("click", function() {
  img = document.getElementById("image-container");
  img.style.display = img.style.display === "none" ? "block" : "none";
})
#container {
    width: 500px; 
    height: 500px;
    background-color: aquamarine;
}

#div1{
    display: block;
    position: relative;
    width: 100px;
    margin-bottom: 8px;
    background-color: burlywood;
    min-height: 100px; /*add a min-height here*/
}

#div2{
    display: block;
    width: 100%;
    height: 100px;
    background-color: red;
}

#image-container > img{
    width: 90px; 
    position: absolute;
    margin-right: 10px;
    margin-top: 10px;
}
<div id="div1">
  <div id="image-container">
    <img src="https://natureconservancy-h.assetsadobe.com/is/image/content/dam/tnc/nature/en/photos/Zugpsitze_mountain.jpg?crop=0,176,3008,1654&wid=4000&hei=2200&scl=0.752" alt="nature"></img>
  </div>
</div>

<div id="div2">
  <button id="show-hide">Show hide image</button>
</div>

只需从您的图片中删除 position: absolute; - 没有必要,这就是导致重叠的原因,因为由于该位置设置,它可以“走出”其父级,从而将其删除文档流,使其在位置上依赖于其父元素,但不将其视为父元素“内部”的内容。