z-index不起作用的大坑
阿新 • • 發佈:2018-11-05
話說好久就沒有更新部落格了,今天為了裝一把,差點沒把自己裝進去。。。以後還是低調一點好,哈哈,話不多說,直奔主題。
今天遇到的就是z-index不起作用的問題。一個後臺小哥不知道抽什麼瘋,寫元素覆蓋偏不讓用absolute,搞的我之後廢了9牛二虎之力寫了一下,問題描述是這樣的,
一對兄弟節點,insert和parent,parent有兩個子節點subtop和subbottom,展現的結果是想讓subtop在insert上面,subbottom在insert下面,
程式碼如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> .insert{ position: relative; z-index:100; background: green; width:300px; height:300px; top:100px; } .parent{ /*position:relative; z-index: 1000;*/ width:200px; height:200px; /*left:0; top:-50px;*/ border:1px solid #eee; } .subbottom{ position:relative; z-index: 50; width:200px; height:200px; background: red; top:-100px; left:0; } .subtop{ position: relative; z-index:1100; width:100px; height:100px; left:0; top:0; background: blue; } </style> </head> <body> <div class="insert"></div> <div class="parent"> <div class="subtop"></div> <div class="subbottom"></div> </div> </body> </html>
其實原理也很簡單,就是利用了z-index的覆蓋問題,在寫的過程中我發現無論怎麼改變,insert的z-index總是無效的,於是百度了一下z-index無效的情況,一共有三種:
1、父標籤 position屬性為relative;
2、問題標籤無position屬性(不包括static);
3、問題標籤含有浮動(float)屬性。
這樣也很好理解為什麼parent設定了position和z-index之後insert的z-index就會失效的問題了,他的解決辦法有是三個:
1、position:relative改為position:absolute;
2、浮動元素新增position屬性(如relative,absolute等);
3、去除浮動。
所以,去掉parent的position和z-index,達到了我想要的效果,如下圖所示: