在容器 div 后面放置 2 divs(顶部底部)

Placing 2 divs (top bottom) behind container div

我正在尝试将背景 div 放在容器后面。我想我会在顶部放置一个 div,在底部放置一个。然后让容器有一个position:relative。但只有顶部在容器后面。这是它的样子

http://oi62.tinypic.com/2lm3mvk.jpg

这就是我想要的样子

http://oi57.tinypic.com/5zjjvs.jpg

两个蓝色 div 应该在后面,棕色 div 是容器。红色的 div 是 header/footer。我应该怎么做?

 <body>
        <div id="wrapper">
            <div id="top"></div>
            <div class="blueLeft"></div>
            <div class="padding"></div>
            <div id="container"></div>
            <div class="blueRight"></div>
            <div id="bottom"></div>


        </div>
    </body>

#wrapper{
    width:100%;
    height:100%;
}

#top,#bottom{
    background-color: red;
    width:100%;
    height:200px;
    clear:both;
}

#container{
    background-color: brown;
    width:800px;
    height:600px;
    margin:0 auto;
    position: relative;
}

.blueLeft{
    width: 100%;
    height: 200px;
    background-color: blue;
    float:left;
}

.blueRight{
    width: 100%;
    height: 300px;
    background-color: blue;
    float:right;
}

使用您的示例,您可以只给 #container 一个等于第二个蓝色 div.

高度的负边距

例如:

#wrapper{
    width:100%;
    height:100%;
}

#top,#bottom{
    background-color: red;
    width:100%;
    height:200px;
    clear:both;
}

#container{
    background-color: brown;
    width:800px;
    height:600px;
    margin:0 auto;
    position: relative;
    margin-bottom: -300px;
}

.blueLeft{
    width: 100%;
    height: 200px;
    background-color: blue;
    float:left;
}

.blueRight{
    width: 100%;
    height: 300px;
    background-color: blue;
    float:right;
}
<body>
<div id="wrapper">
  <div id="top"></div>
  <div class="blueLeft"></div>
  <div class="padding"></div>
  <div id="container"></div>
  <div class="blueRight"></div>
  <div id="bottom"></div>

</div>
  </body>

但是,您可能需要考虑换一种方式。

您遇到的问题不是您的 #container 元素是底部蓝色浮动的 "on top" Z 轴方式,而是它在文档中垂直位于其上方(基本上,浮动正在清除您的 #container.

尝试将 margin-top: -300px; 添加到您的 .blueRight CSS 中,看看是否能满足您的需求。

看看这是不是你想要的。

http://jsfiddle.net/vleong2332/pq3823tz/

<div id="wrapper">
    <div id="top"></div>
    <div class="blueTop"></div>
    <div class="padding"></div>
    <div id="container"></div>
    <div class="blueBottom"></div>
    <div id="bottom"></div>
</div>

CSS

#wrapper{
    width:100%;
    height:100%;
    position: relative;
}
#top,#bottom{
    background-color: red;
    width:100%;
    height:200px;
    clear:both;
}
#container{
    background-color: brown;
    width:800px;
    height:600px;
    margin:0 auto;
    position: relative;
}
.blueTop{
    width: 100%;
    height: 200px;
    background-color: blue;
    position: absolute;
}
.blueBottom{
    width: 100%;
    height: 300px;
    background-color: blue;
    position: absolute;
    bottom: 200px;
    z-index: -1;
}

在 HTML,我将 class 更改为 blueTop 和 blueBottom,因为它们在语义上会更准确。

在 CSS,因为我认为您不需要浮动,所以我删除了它们。我在蓝色 divs 上使用了 position: absolute 。最上面的不需要重新调整,因为流程已经把它放在你想要的地方了。对于底部,我需要将底部放在红色的顶部,因为它与正常流动相反。 z-index就是把blueBottom放在brown后面div.

希望这对您有所帮助。