【问题标题】:Image in the top div always hide the bottom div with a negative margin顶部 div 中的图像始终以负边距隐藏底部 div
【发布时间】:2014-03-03 06:59:06
【问题描述】:

我创建了两个 div,一个堆栈在另一个之上。顶部 div 包含以块显示的图像。底部 div 具有负边距和背景颜色。但是,底部div与顶部div重叠的部分的背景色无法显示,尽管底部div中的内容显示在顶部div的顶部。如何在顶部 div 的顶部也显示背景颜色?

以下是代码,现场演示可从此处获得:http://jsfiddle.net/spencerfeng/6XFau/

HTML:

<div id="container">
<div id="container1">
    <img class="responsive-img" src="http://www.fubiz.net/wp-content/uploads/2013/07/One-Ocean-One-Breath14.jpg" alt="">
</div>
<div id="container2">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse dapibus pretium orci, ac tristique mauris tincidunt sit amet. Vestibulum ornare in felis non fringilla.</p>
</div>
    </div>

CSS:

#container {
    width:300px;
    margin-left:auto;
    margin-right:auto;
}
#container1 img {
    display:block;
    width:100%;
    height:auto;
}
#container2 {
    width:100%;
    height:200px;
    background:red;
    margin-top:-50px;
}

【问题讨论】:

  • 即使我不明白为什么会这样?根据有关堆叠上下文的规范,dom 中稍后出现的内容不应该与先前的元素重叠吗?因为默认情况下 img 标签的位置值是静态的,所以任何静态位置的内容都应该与 img 重叠,如果它稍后出现在 dom 中。一个详细的答案将不胜感激。谢谢

标签: html css margin


【解决方案1】:

从 p 中删除默认边距:

p{margin:0}

并从第二个 div 中删除负边距顶部:

#container2 {
    width:100%;
    height:200px;
    background:red;
    margin-top:0;
}

如果这就是您所追求的,这两个框应该完美对齐

【讨论】:

    【解决方案2】:

    如果您需要红色 div 顶部与图像重叠,您应该使用如下相对定位

    JSFiddle Demo

    CSS

    #container {
        width:300px;
        margin-left:auto;
        margin-right:auto;
    }
    #container1 img {
        display:block;
        width:100%;
        height:auto;
    }
    #container2 {
        width:100%;
        height:200px;
        background:red;
        position:relative;
        top:-50px;
    }
    

    【讨论】:

      【解决方案3】:

      将这两个属性用于底部 div:

      position:relative;
      z-index:999999;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-06-15
        • 2014-02-05
        • 2010-12-18
        • 2020-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多