所以如果我正确理解z-index,它在这种情况下是完美的:

我想把底部图像(标签/卡片)下面的div上面。所以你看不到锋利的边缘。我怎么做呢?

z-index:-1 // on the image tag/card

or

z-index:100 // on the div above

也不管用。像这样的组合也不行。如何来吗?


当前回答

你的元素需要有一个position属性。(例如绝对指数、相对指数、固定指数)或z指数都不起作用。

其他回答

我在z指数上也遇到过同样的问题 不管你信不信,只要设置背景色就能解决问题

像这样

背景颜色:白色;

在很多情况下,一个元素必须被定位到z-index才能工作。

实际上,应用position:相对于问题中的元素可能会解决问题(但没有提供足够的代码来确定)。

实际上,position: fixed, position: absolute和position: sticky也会启用z-index,但这些值也会改变布局。与位置:相对布局不会被打乱。

本质上,只要元素不是position: static(默认设置),它就被认为是定位的,z-index就可以工作。


许多关于“为什么z-index不起作用?”的问题的答案都断言,z-index只对已定位的元素起作用。从CSS3开始,这种情况就不再存在了。

弹性项目或网格项目的元素即使在位置是静态的情况下也可以使用z-index。

从规格来看:

4.3. Flex Item Z-Ordering Flex items paint exactly the same as inline blocks, except that order-modified document order is used in place of raw document order, and z-index values other than auto create a stacking context even if position is static. 5.4. Z-axis Ordering: the z-index property The painting order of grid items is exactly the same as inline blocks, except that order-modified document order is used in place of raw document order, and z-index values other than auto create a stacking context even if position is static.

以下是z-index在非定位伸缩项目上的演示:https://jsfiddle.net/m0wddwxs/

你的元素需要有一个position属性。(例如绝对指数、相对指数、固定指数)或z指数都不起作用。

确保您想要使用z-index控制的元素没有具有z-index属性的父元素,因为元素由于其父元素的z-index级别而处于较低的堆叠上下环境中。

这里有一个例子:

<section class="content">            
    <div class="modal"></div>
</section>

<div class="side-tab"></div>

// CSS //
.content {
    position: relative;
    z-index: 1;
}

.modal {
    position: fixed;
    z-index: 100;
}

.side-tab {
    position: fixed;
    z-index: 5;
}

在上面的例子中,模态的z指数比内容高,尽管内容会出现在模态的顶部,因为“content”是具有z-index属性的父元素。

这里有一篇文章解释了z-index可能不起作用的4个原因: https://coder-coder.com/z-index-isnt-working/

如果所有这些都失败了,请在HTML中查找语法错误。这不是直观的,但我看到它是z指数不起作用的原因。

下面的代码有无效的HTML语法:

<div class="over"/>
<div class="under"/>

...(这是无效的语法,因为div不是一个自关闭标签)。

应用于这些流氓HTML元素的CSS属性,如background-color: black、position: fixed、width: 150px和top:150px,都能正常工作。然而,z-index: 2属性在完全相同的条件下并不适用。

只有当无效的HTML被修复时,z-index才能正常工作。

我不确定为什么z-index比其他CSS属性更挑剔,但也许这个答案可以帮助到一些人。