我有一些带有两个div的HTML:
<div>
<div id="backdrop"><img alt="" src='/backdrop.png' /></div>
<div id="curtain" style="background-image:url(/curtain.png);background-position:100px 200px; height:250px; width:500px;"> </div>
</div>
我希望第二个div #curtain
出现在div #backdrop
的顶部。两个div的大小相同,但是我不确定如何将第二个div放在另一个div之上。
答案 0 :(得分:45)
在每个DIV的position: absolute;
属性中使用CSS top: 0px; left 0px;
后跟style
。用你想要的任何东西替换像素值。
您可以使用z-index: x;
设置垂直“顺序”(哪一个是“在顶部”)。将x
替换为数字,较高的数字替换为较低的数字。
以下是新代码的外观:
<div>
<div id="backdrop" style="z-index: 1; position: absolute; top: 0px; left: 0px;"><img alt="" src='/backdrop.png' /></div>
<div id="curtain" style="z-index: 2; position: absolute; top: 0px; left: 0px; background-image:url(/curtain.png);background-position:100px 200px; height:250px; width:500px;"> </div>
</div>
答案 1 :(得分:23)
有很多方法可以做到这一点,但这非常简单,避免了破坏内联内容定位的问题。您可能还需要调整边距/填充。
#backdrop, #curtain {
height: 100px;
width: 200px;
}
#curtain {
position: relative;
top: -100px;
}
答案 2 :(得分:9)
要在另一个div之上正确显示一个div,我们需要使用属性position
,如下所示:
position: relative
position: absolute
我找到了一个很好的例子here:
.dvContainer {
position: relative;
display: inline-block;
width: 300px;
height: 200px;
background-color: #ccc;
}
.dvInsideTL {
position: absolute;
left: 0;
top: 0;
width: 150px;
height: 100px;
background-color: #ff751a;
opacity: 0.5;
}
&#13;
<div class="dvContainer">
<table style="width:100%;height:100%;">
<tr>
<td style="width:50%;text-align:center">Top Left</td>
<td style="width:50%;text-align:center">Top Right</td>
</tr>
<tr>
<td style="width:50%;text-align:center">Bottom Left</td>
<td style="width:50%;text-align:center">Bottom Right</td>
</tr>
</table>
<div class="dvInsideTL">
</div>
</div>
&#13;
我希望这有帮助,
字形。
答案 3 :(得分:1)
以下是jsFiddle
#backdrop{
border: 2px solid red;
width: 400px;
height: 200px;
position: absolute;
}
#curtain {
border: 1px solid blue;
width: 400px;
height: 200px;
position: absolute;
}
使用Z-index移动您想要的顶部。
答案 4 :(得分:0)
将父div和子div的样式设置如下。它适用于我的情况,希望对您有帮助。
<div id="parentDiv">
<div id="backdrop"><img alt="" src='/backdrop.png' /></div>
<div id="curtain" style="background-image:url(/curtain.png);background-position:100px 200px; height:250px; width:500px;"> </div>
</div>
在您的JS中:
document.getElementById('parentDiv').style.position = 'relative';
document.getElementById('backdrop').style.position = 'absolute';
document.getElementById('curtain').style.position = 'absolute';
document.getElementById('curtain').style.zIndex= '2';//this number has to be greater than the zIndex of 'backdrop' if you are setting any
或在本工作示例中的CSS中:::
#parentDiv{
background: yellow;
height: 500px;
width: 500px;
position: relative;
}
#backdrop{
background: red;
height: 300px;
width: 300px;
position: absolute;
}
#curtain{
background: green;
height: 100px;
width: 100px;
position: absolute;
z-index: 2;
margin: 100px 0px 150px 100px;
}
<div id="parentDiv"><h2>
THIS IS PARENT DIV
</h2>
<div id="backdrop"><h4>
THIS IS BACKDROP DIV
</h4></div>
<div id="curtain"><h6>
THIS IS CURTAIN DIV
</h6></div>
</div>