深入理解 CSS 层叠上下文 z-index

2025-12-27 2144阅读

在 CSS 中,z-index 是一个非常重要的属性,它用于控制元素在三维空间中的堆叠顺序,也就是层叠上下文。

简单来说,当多个元素重叠时,z-index 值较大的元素会显示在上面。例如:

<!DOCTYPE html>
<html>

<head>
    <style>
       .box1 {
            position: relative;
            width: 200px;
            height: 200px;
            background-color: lightblue;
            z-index: 1;
        }

       .box2 {
            position: relative;
            width: 100px;
            height: 100px;
            background-color: lightcoral;
            z-index: 2;
        }
    </style>
</head>

<body>
    <div class="box1"></div>
    <div class="box2"></div>
</body>

</html>

这里 box2 的 z-index 为 2,大于 box1 的 z-index 为 1,所以 box2 会覆盖在 box1 之上。

需要注意的是,z-index 只有在元素的 position 属性值为 relative、absolute 或 fixed 时才有效。并且,它仅仅影响定位元素之间的层叠关系。

在复杂的页面布局中,合理运用 z-index 可以实现很多有趣的效果,比如创建模态框、悬浮菜单等。但也要谨慎使用,避免出现层叠混乱的情况。总之,深入理解 z-index 对于打造优秀的页面视觉效果至关重要。

文章版权声明:除非注明,否则均为Dark零点博客原创文章,转载或复制请以超链接形式并注明出处。