# CSS定位(二)

# position

  • static 默认值,待在文档流
  • relative 相对定位,升起来,但不脱离文档流
  • absolute 绝对定位,定位基准是祖先元素中最近的非static
  • fixed 固定定位,定位基准是viewport
  • sticky 粘滞定位

# position:relative

  <div class="container">
    <div class="demo"></div>
    <div class="demo2"></div>
  </div>
.demo{
  border:1px solid green;
  background-color: green;
  width:50px;
  height:50px;
  position:relative;
  top:10px;
  left:10px;
}
.demo2{
  width:50px;
  height:50px;
  background-color: black;
}

# z-index

  • z-index:auto为默认值,不创建新层叠上下文
  • z-index:0/1/2
  • z-index:-1/-2
.demo{
  position:relative;
}
.demo2{
  position:relative;
  z-index:-1;
}

# position:absolute

  • 脱离原来位置,另起一层(比如对话框关闭按钮)
  <div class="container">
    <span class="close">X</span>
  </div>
.container{
  border:1px solid red;
  height:400px;
  position:relative;
}
.close{
  position:absolute;
  top:0;
  right:0;
  padding:2px 8px;
  background-color: grey;
  color:white
}

  • 鼠标提示
    <button>
      点击
      <span class="tips">提示内容</span>
    </button>
button{
  position:relative;
}
button > .tips{
  position:absolute;
  border:1px solid green;
  white-space:nowrap;
  bottom:calc(100% + 10px);
  left:50%;
  transform: translateX(-50%);
}
button > .tips{
  display:none;
}
button:hover > .tips{
  display:inline-block;
}

# position:fixed

 <div class="container">
    <div class="fixed"></div>
 </div>
.container{
  border:1px solid red;
  height:400px;
}
.fixed{
  position:fixed;
  width:50px;
  height:50px;
  background-color: red;
  bottom:200px;
  left:10px;
}

# position:sticky

.sticky{
  position:-webkit-sticky;
  position:sticky;
  top:0;
  border:1px solid green;
  background-color: red;
}

1.gif