一對兄弟節點,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,達到了我想要的效果。






