position定位及各自应用在什么场景

  • static:默认。位置设置为 static 的元素,它始终会处于页面流给予的位置(static 元素会忽略任何top、bottom、left 或 right 声明),相当于没有定位,基本上用不到这个属性。
  • relative:相对于自己在文档流中原本的位置进行定位,不脱离文档流,原来位置留下空白,如果想要盒子偏离自己原本的位置,却保留在文档流中,可以使用relative
  • absolute:应用了absolute的元素会相对于最近的非static定位的祖先元素偏移,如果祖先元素没有设置过非static定位属性时,则该元素最终以html元素进行位置偏移,如果我们想实现一个子元素,在父元素内部水平居中,那么父元素可以设置为relative,子元素设置为absolute
  • fixed:固定定位。会脱离文档流,覆盖到非定位元素上,absolute的参照物是可以被设置的,而fixed的参照物固定为浏览器窗口。即当你滚动网页,其元素与浏览器窗口之间的距离是恒定不变的。
  • sticky:粘贴。设置top,right,left,bottom阈值,父节点必须是overflow:visible才能生效,任意父节点定位设置为position:relative | absolute | fixed,则元素相对父元素进行定位,而不会相对 viewport 定位

可以运行代码体会一下

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    *{
      text-align: center;
      line-height: 100px;
    }
    .first{
      width: 100px;
      height: 100px;
      background-color: red;
      /* 默认就有这句,写不写,没什么影响,效果图都一样 */
      position: static;
    }
    .second{
      width: 100px;
      height: 100px;
      background-color: green;
      position: relative;
      top:15px;
      left: 15px;
    }
    .third{
      width: 100px;
      height: 100px;
      background-color: yellow;
      position: absolute;
      top:30px;
      left:80px;
    }
    .forth{
      width: 100px;
      height: 100px;
      background-color: pink;
      position: fixed;
      top:200px;
      left:200px;
    }
    .fifth{
      width: 100px;
      height: 100px;
      background-color: pink;
      position: sticky;
      top:50px;
    }
    .transparent{
      width: 100px;
      height: 700px;
    }
  </style>
</head>
<body>
  <div class="first">我是static</div>
  <div class="second">我是ralative</div>
  <div class="third">我是absolute</div>
  <div class="forth">我是fixed</div>
  <div class="fifth">我是sticky</div>
  <div class="transparent"></div>
</body>
</html>

版权声明:本文为rainylululululu原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。