【问题标题】:CSS - prevent relative div with unknown height from overlapping the div below [closed]CSS - 防止具有未知高度的相对 div 与下面的 div 重叠 [关闭]
【发布时间】:2021-05-08 03:38:13
【问题描述】:
<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 重叠并保持在其上方?

我还尝试在它们之间放置&lt;div style="clear: both;"&gt;&lt;/div&gt;

【问题讨论】:

  • 我认为给定的代码不会重现您描述的问题。请创建一个minimal reproducible example 进行演示...
  • 同意,显示的代码会导致 div 重叠
  • 好的,我编辑了问题,检查一下
  • 指定min-height。这样即使有一个空元素,它仍然会占用空间。
  • @ProsyArceno nope 不能那样工作,当我指定最小高度 5px 时,它只会上升 5px 就这样。上帝的 CSS 太糟糕了

标签: html css css-position


【解决方案1】:

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

【讨论】:

  • 有需要。右上角会有一个“关闭”的图像,部分覆盖图像
  • 那么“关闭”的图片需要绝对位置,而不是作为父元素内容的图片。
  • 天哪,你是对的 xD 只有“关闭”图像需要绝对位置,谢谢!
【解决方案2】:

我复制了你的样式。我刚刚添加了一个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>

【讨论】:

  • div1 中没有 position: relative,宽度必须为 100px,并且图像没有 position: absolute。我想这是不可能的:/
  • 我修改了代码。
  • 它只会上升到定义的最小高度,这不是一个解决方案抱歉。我一开始想要的方式似乎是不可能的
猜你喜欢
  • 1970-01-01
  • 2014-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-17
  • 2020-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多