CSS 中的z-index属性

z-index

z-index :auto|<integer>      auto 默认值   

定义:一个元素在文档中的层叠顺序,用于确认元素在当前层叠上下文中的层叠级别。

适用于:定位元素。即定义了position为非static的元素

每个元素层叠顺序由所属的层叠上下文元素本身的层叠级别决定(每个元素仅属于一个层叠上下文)。

1、同一层叠上下文

层叠级别大的显示在上面,级别小的显示在下面;

层叠级别中的两个元素,依据它们在HTML文档流中的顺序,写在后面的将会覆盖前面的。

2、不同层叠上下文

元素的显示顺序依据祖先的层叠级别来决定,与自身的层叠级别无关。


例:

1、有两个div盒子,a、c在一个盒子里,b在另一个盒子里,来考虑其z-index是不是正常效果。

1.	<body>  
2.	    <div>  
3.	        <p class="a">a</p>  
4.	        <p class="c">c</p>  
5.	    </div>  
6.	    <div>  
7.	        <p class="b">b</p>  
8.	    </div>  
9.	</body>  

div未设置z-index,在高级浏览器下不会产生新的局部层叠上下文,也就是说它们的子元素没有被新的局部层叠上下文包裹,那么它们的子元素就处在同一个层叠上下文中,可以直接通过自身的层叠级别来决定显示顺序。

1.	div {  
2.	       position: relative;  
3.	       width: 100px;  
4.	       height: 100px;  
5.	    }  
6.	  p {  
7.	       position: absolute;  
8.	       font-size: 20px;  
9.	       width: 100px;  
10.	       height: 100px;  
11.	    }  
12.	 .a {  
13.	       background-color: pink;  
14.	       z-index: 1;  
15.	    }  
16.	          
17.	 .c {  
18.	       background-color: green;  
19.	       z-index: 2;  
20.	       top: 20px;  
21.	       left: 20px;  
22.	    }  
23.	 .b {  
24.	       background-color: red;  
25.	       z-index: 3;  
26.	       top: -20px;  
27.	       left: 40px;  
        }  

a、b、c处于一个层叠上下文中,所以根据z-index大小来确定层级。如下图所示:

2、有两个div盒子,a、c在一个盒子里,b在另一个盒子里,来考虑其z-index是不是正常效果。

<body>
	<div class="box1">
		<p class="a">a</p>
		<p class="c">c</p>
	</div>
	<div class="box2">
		<p class="b">b</p>
	</div>
</body>

div设置z-index,那么div中的子元素以父元素的层叠关系为主。

<style type="text/css">
		div {
			width: 100px;
			height: 100px;
			position: relative;
		}
		.box1 {
			z-index: 2;
		}
		.box2 {
			z-index: 1;
		}
		p {
			position: absolute;
			font-size: 20px;
			width: 100px;
			height: 100px;
		}
		.a {
			background-color: red;
		}
		.c {
			background-color: green;
			top: 20px;
			left: 20px;
		}
		.b {
			background-color: blue;
			top: -20px;
			left: 40px;
			z-index: 20;
		}
	</style>

a、b、c处于不同的层叠上下文中,所以根据父级的z-index大小来确定层级。如下图所示:

由上,可以看出z-index的决定方式:所属的层叠上下文元素本身的层叠级别

猜你喜欢

转载自blog.csdn.net/weixin_40672882/article/details/81183321