为什么z-index不起作用?

时间:2017-01-16 21:32:36

标签: html css position z-index

我有简单的html和css代码:

HTML:

<div class="header">
    <div class="tip"></div>
</div>

CSS:

.header {
    display: block;
    width: 260px;
    min-height: 222px;
    background-color: #252525;
    position: relative;
    z-index: 5;
    -webkit-box-shadow: 0 0 5px #000;
    -moz-box-shadow: 0 0 5px #000;
    box-shadow: 0 0 5px #000;
    border-radius: 2px;
}
.tip {
    display: inline-block;
    width: 10px;
    height: 10px;
    right: 11px;
    top: -5px;
    transform: rotateZ(45deg);
    position: absolute;
    z-index: 1;
    background-color: red;
    -webkit-box-shadow: 0 0 5px #000;
    -moz-box-shadow: 0 0 5px #000;
    box-shadow: 0 0 5px #000;

}

我只想.tip块在.header块下。 但现在它看起来像这样,虽然.tip的z索引小于.header的z索引: enter image description here

这就是我想要的:enter image description here

出于某种原因,z-index不起作用。 我需要在.header块上设置z-index,因为我在页面上还有另一个具有z-index的块

2 个答案:

答案 0 :(得分:2)

要使父元素的子元素具有比父元素更高的z-index,请删除父元素的z-index值。

&#13;
&#13;
.header {
    display: block;
    width: 260px;
    min-height: 222px;
    background-color: #252525;
    position: relative;
    /*z-index: 5;*/
    -webkit-box-shadow: 0 0 5px #000;
    -moz-box-shadow: 0 0 5px #000;
    box-shadow: 0 0 5px #000;
    border-radius: 2px;
}
.tip {
    display: inline-block;
    width: 10px;
    height: 10px;
    right: 11px;
    top: -5px;
    transform: rotateZ(45deg);
    position: absolute;
    z-index: -1;
    background-color: red;
    -webkit-box-shadow: 0 0 5px #000;
    -moz-box-shadow: 0 0 5px #000;
    box-shadow: 0 0 5px #000;
}
&#13;
<div class="header">
    <div class="tip"></div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

尝试将1更改为-1 ...并删除第一个块(标题)中的z-index:5;看看这部分代码:

.header {
    display: block;
    width: 260px;
    min-height: 222px;
    background-color: #252525;
    position: relative;
    -webkit-box-shadow: 0 0 5px #000;
    -moz-box-shadow: 0 0 5px #000;
    box-shadow: 0 0 5px #000;
    border-radius: 2px;
}

.tip {
    display: inline-block;
    width: 10px;
    height: 10px;
    right: 11px;
    top: -5px;
    transform: rotateZ(45deg);
    position: absolute;
    z-index: -1;
    background-color: red;
    -webkit-box-shadow: 0 0 5px #000;
    -moz-box-shadow: 0 0 5px #000;
    box-shadow: 0 0 5px #000;

}