最近在作一個動畫的時候,把動畫元素的樣式設置以下,但絲絕不起做用。css
.animate{
display:block;
z-index:9999;
position:absute;
}
複製代碼
這幾天正好有時間,找了不少資料,來探究css如何控制html元素的堆疊秩序html
要弄清楚z-index不起做用的緣由,須要回答如下三個問題:
1.什麼是堆疊上下文(Stacking Contexts)?
2.如何造成堆疊上下文?
3.在同一個堆疊中元素如何堆疊(即在z軸方向上如何排序)?bash
堆疊上下文和BFC有點相似,具備共同父元素的一組元素按堆疊順序一塊兒向前或向後移動,構成所謂的堆疊上下文。每一個堆疊上下文中的元素相互不影響。flex
要造成一個堆疊上下文只需知足如下條件中的一個:動畫
我須要把綠色的方塊放到最上面 ui
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
div:nth-child(2) {
opacity: .99;
display: block;
z-index: 9999;
}
.red, .green, .blue {
position: absolute;
width: 100px;
color: white;
line-height: 100px;
text-align: center;
}
.red {
top: 20px;
left: 20px;
background: red;
}
.green {
top: 60px;
left: 60px;
background: green;
display: block;
z-index: 9999;
}
.blue {
top: 100px;
left: 100px;
background: blue;
}
</style>
</head>
<body>
<div>
<span class="red">Red</span>
</div>
<div>
<span class="green">Green</span>
</div>
<div>
<span class="blue">Blue</span>
</div>
</body>
</html>
複製代碼
只需把 div:nth-child(2) { opacity: .99; }這個去掉綠色快就顯示到最上面了spa
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>CSS中的堆疊上下文</title>
<style>
div {
padding: 10px;
text-align: center;
}
#abs1 {
position: absolute;
width: 150px;
height: 200px;
top: 10px;
right: 140px;
border: 1px dashed #900;
background-color: #fdd;
}
#sta1 {
height: 100px;
border: 1px dashed #996;
background-color: #ffc;
margin: 0px 10px 0px 10px;
text-align: left;
}
#flo1 {
margin: 0px 10px 0px 20px;
float: left;
width: 150px;
height: 200px;
border: 1px dashed #090;
background-color: #cfc;
}
#flo2 {
margin: 0px 20px 0px 10px;
float: right;
width: 150px;
height: 200px;
border: 1px dashed #090;
background-color: #cfc;
}
#abs2 {
position: absolute;
width: 150px;
height: 100px;
top: 130px;
left: 100px;
border: 1px dashed #990;
background-color: #fdd;
}
#relat {
position: relative;
width: 150px;
height: 100px;
top: 30px;
left: 100px;
border: 1px dashed #990;
background-color: #fdd;
}
</style>
</head>
<body>
<div id="abs1">
<h2>DIV #1</h2>position: absolute;
</div>
<div id="flo1">
<h2>DIV #2</h2>float: left;
</div>
<div id="flo2">
<h2>DIV #3</h2>float: right;
</div>
<div id="sta1">
<h2>DIV #4</h2>no positioning
</div>
<div id="relat">
<h2>DIV #5</h2>
position: relative
</div>
</body>
</html>
複製代碼