我的问题很简单,我有两个div,其中一个有绝对位置。我将绝对位置div的z-index设置为最低值,将另一个设置为最高值但始终保持绝对位置的z-index保持在最顶层(相反的行为)。
这里有一张图片:
这里有代码:
<div style="position:relative;">
<div style="position:absolute;width:200px;background-color:#ff0;z-index:1;">
SHOULD BE ON BACK. SHOULD BE ON BACK. SHOULD BE ON BACK.
SHOULD BE ON BACK. SHOULD BE ON BACK.
</div>
<div style="width:300px;background-color:#0f0;z-index:999999;">
SHOULD BE ON FRONT. SHOULD BE ON FRONT.
SHOULD BE ON FRONT. SHOULD BE ON FRONT.
</div>
</div>
看看下面的jsfiddle:
答案 0 :(得分:0)
为“应该在前面添加
position: absolute;
元素
注意: z-index
仅影响position
值不是static
的元素(默认值)。
<div style="position:relative;">
<div style="position:absolute;width:200px;background-color:#ff0;z-index:1;">
SHOULD BE ON BACK. SHOULD BE ON BACK. SHOULD BE ON BACK.
SHOULD BE ON BACK. SHOULD BE ON BACK.
</div>
<div style="width:300px;background-color:#0f0;z-index:999999;position:absolute;">
SHOULD BE ON FRONT. SHOULD BE ON FRONT.
SHOULD BE ON FRONT. SHOULD BE ON FRONT.
</div>
</div>
答案 1 :(得分:0)
您需要摆脱父div中的样式并将样式添加到前div中。将int
error
none
error
error
none
none
none
none
添加到'这应该在前面'。
因此:
position:relative
注意:z-index仅适用于定位元素(位置:绝对,位置:相对或位置:固定)。 -W3Schools,来自here
答案 2 :(得分:0)
将您的第二个div更新为
<div style="position:relative;width:300px;background-color:#0f0;z-index:999999;">
SHOULD BE ON FRONT. SHOULD BE ON FRONT.
SHOULD BE ON FRONT. SHOULD BE ON FRONT.
</div>
只有当DIV有一个位置设置(相对,绝对,固定等)时,Z-index才会适用 - 所以两个div都需要一个位置,而不仅仅是一个位置。
答案 3 :(得分:0)
你的标记应该是这样的。
<div style="position:relative;">
<div style="position:absolute;width:200px;background-color:#ff0;z-index:1;">
SHOULD BE ON BACK. SHOULD BE ON BACK. SHOULD BE ON BACK.
SHOULD BE ON BACK. SHOULD BE ON BACK.
</div>
<div style="position:relative;width:300px;background-color:#0f0;z-index:2;">
SHOULD BE ON FRONT. SHOULD BE ON FRONT.
SHOULD BE ON FRONT. SHOULD BE ON FRONT.
</div>
</div>
检查此更新的Fiddle
答案 4 :(得分:0)
您可以将第一个div的z-index更改为-1,或将position:relative
或position:absolute
添加到第二个div。
答案 5 :(得分:-1)
你去...... 应该在前面并不是绝对的并且在前面:P
<div style="position:relative;">
<div style="position:absolute;width:200px;background-color:red;z-index:1;">
SHOULD BE ON BACK. SHOULD BE ON BACK. SHOULD BE ON BACK. SHOULD BE ON BACK. SHOULD BE ON BACK.
</div>
<div style="width:300px;background-color:yellow;z-index:2;position: relative;">
SHOULD BE ON FRONT. SHOULD BE ON FRONT. SHOULD BE ON FRONT. SHOULD BE ON FRONT.
</div>
</div>
答案 6 :(得分:-1)
让第二个div位置绝对......
<div style="position:absolute;width:300px;background-color:#0f0;z-index:999999;">
最终代码将如下所示
<div style="position:relative;">
<div style="position:absolute;width:200px;background-color:#ff0;z-index:1;">
SHOULD BE ON BACK. SHOULD BE ON BACK. SHOULD BE ON BACK.
SHOULD BE ON BACK. SHOULD BE ON BACK.
</div>
<div style="position:absolute;width:300px;background-color:#0f0;z-index:999999;">
SHOULD BE ON FRONT. SHOULD BE ON FRONT.
SHOULD BE ON FRONT. SHOULD BE ON FRONT.
</div>
</div