說起瀏覽器中的元素層級,我們首先能想到的就是z-index,position(值非static)+z-index結合使用,即可控制元素在瀏覽器中的顯示層級。那除了這種方式外,還有其他什么方式可以控制元素的層級呢?
7階層疊水平
任何元素都有層疊順序,當元素發生層疊時,層級高的會顯示在上面,覆蓋層級低的元素。當元素的層級相同時,則會根據DOM的先后順序依次顯示。層疊優先級如下圖所示。(網上找的)

也就是說,當元素發生層疊時,除了z-index設置層級外,display:inline-block > float:left > display:block 也可以控制元素的層級顯示。經過例子驗證,當元素有內容時,內容的層級會更高。
層疊上下文
官方解釋:層疊上下文是HTML元素的三維概念,這些HTML元素在一條假想的相對於面向視點或者網頁的用戶的z軸上延伸,HTML元素依據其自身屬性按照優先級順序占據着層疊上下文的空間。 頁面的根元素<html>具有根層疊上下文。
當元素有層疊上下文時,其層級比普通元素(block元素,float元素等)要高。通過給元素設置如下屬性即可讓元素擁有層疊上下文環境。
1.定位元素中z-index不等於auto,為大於0的值
2.元素設置opacity為不等於1的值
3.元素的transform屬性不為none
4.will-change指定的屬性值為上面任意一個
還有其他的方法,上面的四種是較常用的。給元素設置上面這些屬性后,即可提高元素的層級。提高的層級在z-index:0的位置。當元素都有較高的z-index值時,層疊順序按值的高低排列。當我們遇到元素層疊的現象時,找出元素是屬於哪個層級的,修改元素的屬性或者創建層疊上下文來調整元素的層級。
注意事項:
- z-index的值的比較只能在同個層級上下文環境中,不同父元素的子節點的z-index的值是不能比較的。
- 開發中盡量避免層疊上下文的多層嵌套。避免使用太多的z-index值。
Demo
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" Content="text/html; charset=utf-8;"> <title>層級上下文</title> <style> body{background:#aaa;color:#fff;} .box{margin:0 0 100px;overflow:hidden;} .wrap{width:300px;height:300px;margin-top:-100px;} .wrap-1{position:relative;z-index:-1;background:#f60;margin-top:0;} .wrap-2{display:block;background:#000;} .wrap-3{float:left;background:#23A42B;} .wrap-4{display:inline-block;background:#5171E4;} .wrap-5{position:relative;z-index:auto;background:#53D6EA;} .wrap-6{position:relative;z-index:2;background:#E68787;} .wrap-6-1{margin:0;} .wrap-6-1 .cnt{position:relative;z-index:2;} .wrap-6-2{z-index:1;background:#000;} .wrap-6-2 .cnt{position:relative;z-index:100;} </style> </head> <body> <div class="box"> <h2>Demo1:七個層級的元素</h2> <div class="wrap wrap-1">z-index:-1的層</div> <div class="wrap wrap-2">display:block的層</div> <div class="wrap wrap-3">float的層</div> <div class="wrap wrap-4">display:inline-block的層</div> <div class="wrap wrap-5">z-index:auto/0的層</div> <div class="wrap wrap-6">z-index > 0的層</div> </div> <div class="box"> <h2>Demo2:inline-block的元素層級比block要高</h2> <div class="wrap wrap-4">display:inline-block的層</div> <div class="wrap wrap-2">display:block的層</div> </div> <div class="box"> <h2>Demo3:使用opacity使元素擁有層疊上下文</h2> <div class="wrap wrap-4">display:inline-block的層</div> <div class="wrap wrap-2" style="opacity:0.8;">display:block的層</div> </div> <div class="box"> <h2>Demo4:使用transform使元素擁有層疊上下文</h2> <div class="wrap wrap-4">display:inline-block的層</div> <div class="wrap wrap-2" style="transform:rotate(3deg);">display:block的層</div> </div> <div class="box"> <h2>Demo5:不同父元素的子節點的層級比較</h2> <div class="wrap wrap-6 wrap-6-1"> <div class="cnt">z-index:2,子元素z-index:2的層</div> </div> <div class="wrap wrap-6 wrap-6-2"> <div class="cnt">z-index:1,子元素z-index:100的層<div> </div> </div> </body> </html>
參考:
http://www.cnblogs.com/bfgis/p/5440956.html、
http://www.zhangxinxu.com/wordpress/2016/01/understand-css-stacking-context-order-z-index/
