如何让一个div在另一个div背后?

33

我正试图让 "box-left-mini" 在下方的 div 前面显示。

<div class="box-left-mini">
   this div is infront
    <div style="background-image:url(/images/hotcampaigns/campaign-sample.png);height:100px;width:100px;">
        this div is behind
    </div>
</div>

box-left-mini 的 CSS 为:

.box-left-mini {
    float:left;
    background-image:url(website-content/hotcampaign.png);
    width:292px;
    height:141px;
}

1
使用z-index来实现您想要的结果。 - Rafael
创建一个jsfiddle - JoDev
5个回答

26

你得到很多不同的答案是因为你没有详细解释你想做什么。所有带有代码的答案都是在程序上是正确的,但这取决于你想要实现什么。

.box-left-mini{
    float:left;
    background-image:url(website-content/hotcampaign.png);
    width:292px;
    height:141px;
}

.box-left-mini .front {
    display: block;
    z-index: 5;
    position: relative;
}
.box-left-mini .front span {
    background: #fff
}

.box-left-mini .behind_container {
    background-color: #ff0;
    position: relative;
    top: -18px;
}
.box-left-mini .behind {
    display: block;
    z-index: 3;
}
<div class="box-left-mini">
    <div class="front"><span>this is in front</span></div>
    <div class="behind_container">
        <div class="behind">behind</div>        
    </div>
</div>


这个 jsfiddle 是空的。 - 416E64726577

15
你需要向div元素添加z-index属性,对于顶部的div使用正数,对于下面的div使用负数。
.one {
    
    position:absolute;
    z-index:999;
}


.one {
    position:absolute;
    z-index:-999;
}
<div class="one">
   this div is infront
</div>
    <div class="two">
        this div is behind
    </div>


在 CSS 中,第二个选择器应该是 .two。 - brian

7

总的来说,回答这个问题:

使用z-index可以帮助你控制层叠顺序。参见csstricks上的z-index

具有更高z-index值的元素将显示在具有较低z-index值的元素上方。

例如,请看以下HTML代码:

<div id="first">first</div>
<div id="second">second</div>

如果我有以下的 CSS 样式:
#first {
    position: fixed;
    z-index: 2;
}

#second {
    position: fixed;
    z-index: 1;
}

#first会在#second的上方。

但是针对您的情况:

div元素是要放在前面的div元素的子元素。这在逻辑上是不可能的。


1
一个可能的例子如下:

一个可能的例子如下,

HTML

<div class="box-left-mini">
    <div class="front">this div is infront</div>
    <div class="behind">
        this div is behind
    </div>
</div>

CSS (层叠样式表)
.box-left-mini{
float:left;
background-image:url(website-content/hotcampaign.png);
width:292px;
height:141px;
}
.front{
    background-color:lightgreen;
}
.behind{
    background-color:grey;
    position:absolute;
    width:100%;
    height:100%;
    top:0;
    z-index:-1;
}

http://jsfiddle.net/MgtWS/

但这实际上取决于你的div元素的布局,即它们是否浮动或绝对定位等。

-1

容器不能在内部容器前面。但是尝试以下方法:

CSS:

.container { position:relative; }
    .div1 { width:100px; height:100px; background:#9C3; position:absolute; 
            z-index:1000; left:50px; top:50px; }
    .div2 { width:200px; height:200px; background:#900; }

HTML :

<div class="container">
    <div class="div1">
       Div1 content here .........
    </div>
    <div class="div2">
       Div2 contenet here .........
    </div>
</div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接