# CSS定位(一)

# 1.div的分层

  • background < border
<div class="demo"></div>
.demo{
  width:100px;
  height:100px;
  border:10px solid rgba(255,0,0,0.5);
  background-color: green;
}

  • border < 块级子元素
  <div class="demo">
    <div class="childDiv">
    </div>
  </div>
.demo{
  width:100px;
  height:100px;
  border:10px solid rgba(255,0,0,1);
  background-color: green;
}
.childDiv{
  background-color: white; 
  height:50px;
}

  • 块级子元素 < 浮动元素
  <div class="demo">
    <div class="float"></div>
    <div class="childDiv">
    </div>
  </div>
.demo{
  width:100px;
  height:100px;
  border:10px solid rgba(255,0,0,1);
  background-color: green;
}
.childDiv{
  height:50px;
  background-color: white; 
}
.float{
  float:left;
  height:20px;
  width:20px;
  background-color: black; 
}

  • 浮动元素 < 内联子元素
  <div class="demo">
    <div class="float"></div>
    <span class="text">内联子元素</span>
    <div class="childDiv">
    </div>
  </div>
.demo{
  width:200px;
  height:200px;
  border:10px solid rgba(255,0,0,1);
  background-color: green;
}
.childDiv{
  height:50px;
  background-color: white; 
}
.float{
  float:left;
  height:50px;
  width:50px;
  background-color: black;
}
.text{
  color:red;
  margin-left:-30px;
}

# 结论:Demo

# 2.层叠上下文

# 创建层叠上下文

> 文档根元素(<html>)
> `position`值为 `absolute`或  `relative`且 `z-index`值不为 `auto` 的元素;
> `opacity` 属性值小于 `1` 的元素
> `transform`属性值不为 none 的元素
> flex容器的子元素,且 `z-index`]值不为 `auto`;
<div class=container>
  <div class="a"> 
    <div class="a2">10</div>
  </div>
  <div class="b">
    <div class="b2">5</div>
  </div>
</div>
.container{
  border: 1px solid black;
  height: 200px;
  background: white;
  position: relative;
}
.a{
  border: 1px solid red;
}
.a2{
  position: relative;
  z-index: 10;
  height: 50px;
  width: 50px;
  background: red;
  color:white;
}
.b{
  border: 1px solid green;
}
.b2{
  position: relative;
  z-index: 5;
  height: 50px;
  width: 50px;
  top:-20px;
  background: blue;
  color:white;
  font-size:30px;
}

# 负z-index

# 负z-index无法脱离层叠上下文
  <div class="demo">
    <div class="div"></div>
  </div>
.demo{
  background: rgb(0,255,255);
  width: 200px;
  height: 200px;
  padding: 10px;
  position: relative;
  z-index:0;
}
.demo > .div{
  height: 50px;
  background: red;
  position: relative;
  z-index: -1;
}