📜  z-index 层是如何工作的?

📅  最后修改于: 2021-08-31 06:45:38             🧑  作者: Mango

在本文中,我们将了解 z-index 在 CSS 中的工作原理。众所周知,我们借助维度来查看每一个项目,完全确定一个对象的大小。因此 z-index 用于沿 z 轴渲染元素。 z-index 的默认值为零。

例子:

让我们通过一个例子来理解它。

我们有一些大小相同的纸板,但它们都是不同的颜色。所以如果我们想看到他们在一起,但对我们来说会是这样。

二维

在这里,我们只使用了两个维度,即在 X 维度和 Y 维度上,我们还可以在其中看到 Z 维度。

3D

z-index 的整个概念与 3D 相关,我们可以使用称为 z-index 的属性调整 z 轴。

z 的值也可以是正数、负数或零。

代码实现:

HTML


 

    

 

    
I'm Div One
    
I'm Div Two
    
I'm Div Three
    
I'm Div Four
 


CSS
div {
    width: 140px;
    height: 140px;
    margin: 10px;
    text-align: center;
 
    /* Only display the last div */
    position: absolute;
}
  
/* If we want to adjust the z-axis */
/* use z-index */
.d1 {
    background-color: #79D588;
    top: 50px;
    /* z-index: 10; */
    /* Use comment/uncomment upper
    line to see the difference */
}
  
.d2 {
    background-color: #F6CD6C;
    top: 70px;
    /* z-index: 10; */
    /* Use comment/uncomment upper
    line to see the difference */
}
  
.d3 {
    background-color: #289485;
    top: 90px;
    z-index: 10;
    /* Use comment/uncomment upper
    line to see the difference */
}
  
.d4 {
    background-color: #403E3E;
    top: 110px;
    /* z-index: 10; */
    /* Use comment/uncomment upper
    line to see the difference */
}


CSS (style.css) :

CSS

div {
    width: 140px;
    height: 140px;
    margin: 10px;
    text-align: center;
 
    /* Only display the last div */
    position: absolute;
}
  
/* If we want to adjust the z-axis */
/* use z-index */
.d1 {
    background-color: #79D588;
    top: 50px;
    /* z-index: 10; */
    /* Use comment/uncomment upper
    line to see the difference */
}
  
.d2 {
    background-color: #F6CD6C;
    top: 70px;
    /* z-index: 10; */
    /* Use comment/uncomment upper
    line to see the difference */
}
  
.d3 {
    background-color: #289485;
    top: 90px;
    z-index: 10;
    /* Use comment/uncomment upper
    line to see the difference */
}
  
.d4 {
    background-color: #403E3E;
    top: 110px;
    /* z-index: 10; */
    /* Use comment/uncomment upper
    line to see the difference */
}

注意:可以注释/取消注释每个div的z-index属性,然后一一检查输出。

输出 :

输出