1. 程式人生 > >層疊上下文(z-index)

層疊上下文(z-index)

一、概述

在日常code中,是否遇到過關於層級的問題,下面梳理下各種情況

二、首先來一張著名的7階層疊水平圖


換言之,除了z-index,display:inline-block,float,block也是可以控制元素層級顯示的,ps:當元素有內容的時候,內容的層級會更高。

三、程式碼實現

首先是dom結構和樣式程式碼,這裡body當做是background來看

<body>
	<div class="disblock">display:block</div>
    <div class="zindex-1">z-index:-1</div>
    <div class="float">float</div>
    <div class="disin-block">display:inline-block</div>
    <div class="zindex-0">z-index:0</div>
    <div class="zindex1">正z-index</div>
</body>
<style>
    body{
        background: lightblue;
        color: #fff;
        font-size: 16px;
    }
    .disblock{
        position: relative;
        left: 100px;
        top: 100px;
        width: 500px;
        height: 500px;
        background: hotpink;
    }
    .zindex-1{
        position: relative;
        top: -500px;
        left: 0;
        width: 600px;
        height: 600px;
        background: purple;
        z-index: -1;
    }
    .float{
        position: relative;
        top: -900px;
        left: 200px;
        float: left;
        width: 400px;
        height: 400px;
        background: green;
    }
	.mydiv{
		float: left;
		width: 200px;
		height: 200px;
		background: #fff;
	}
	.mywrap{
		width: 500px;
		height: 500px;
		background: #000;
	}
    .disin-block{
        position: relative;
        top: -800px;
        left: -100px;
        display: inline-block;
        width: 300px;
        height: 300px;
        background: lightgreen;
    }
    .zindex-0{
        position: relative;
        width: 200px;
        height: 200px;
        top: -1000px;
        left: 400px;
        z-index: 0;
        color: #000;
        background: yellow;
    }
    .zindex1{
        position: relative;
        top: -1100px;
        left: 500px;
        width: 100px;
        height: 100px;
        z-index: 1;
        background: red;
    }
</style>
然後是效果圖


四、注意事項

1、z-index的值的比較只能在同個層級上下文環境中,不同父元素的子節點的z-index的值是不能比較的;

2、開發中儘量避免層疊上下文的多層巢狀。避免使用太多的z-index值。