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

时间:2015-03-31 17:08:40

标签: html css css-float

我试图将背景div放在容器后面。我以为我会在顶部放置一个div,在底部放置一个div。然后使容器有一个位置:相对。但只有顶部落后于容器。这就是它的样子

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

这就是我想要的样子

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

两个蓝色div都被置于后面,而褐色div则是容器。红色div是页眉/页脚。我怎么这样做?

 <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;
}

3 个答案:

答案 0 :(得分:0)

使用您的示例,您可以给#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>

但是,您可能需要考虑采用不同的方式。

答案 1 :(得分:0)

您遇到的问题不是您的#container元素是&#34;顶部&#34;您的底部蓝色浮动以Z轴方式显示,它在文档中垂直位于其上方(基本上,浮动正在清除您的#container

尝试将margin-top: -300px;添加到您的.blueRight CSS中,看看是否能为您提供所需内容。

答案 2 :(得分:0)

看看这是否是你想要的。

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上,我将类更改为blueTop和blueBottom,因为它们在语义上更准确。

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

希望这有帮助。

相关问题