CSS中四种定位的区别

版权声明:哼!坏人!这是我辛辛苦苦码的! https://blog.csdn.net/DurianPudding/article/details/87951317

1、默认static

(1)static表示没有定位,或者说不算具有定位属性。
(2)如果元素 position 属性值为 static(或者未设 position 属性),该元素出现在正常的流中(忽略 top, bottom, left, right 或者 z-index 声明)。

2、相对定位relative

占据空间相对于自身原有位置进行偏移,可能会覆盖其他元素。
例如:top: 20px;// 向下移动20px

3、绝对定位absolute

不占空间,相对于最近的已定位的祖先元素, 有已定位(指position不是static的元素)祖先元素, 以最近的祖先元素为参考标准。如果无已定位祖先元素, 以body元素为偏移参照基准。
所以,父元素一般设置为相对定位

4、固定定位fixed

不占空间相对于视窗来定位,这意味着即便页面滚动,它还是会停留在相同的位置。一个固定定位元素不会保留它原本在页面应有的空隙。

实例
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>四种定位的区别</title>
  <style>
    body {
      min-height: 150vh;
    }
    .container {
      width: 200px;
      height: 200px;
      background-color: #111111;
    }

    .main {
      /*
      向下移动20px,覆盖了一部分right
       */
      position: relative;
      top: 20px;

      width: 100px;
      height: 100px;
      background-color: red;
    }

    .right {
      width: 100px;
      height: 100px;
      background-color: green;
    }

    .container2 {
      position: relative;
      width: 200px;
      height: 200px;
      background-color: #111111;
    }

    .main2 {
      position: absolute;
      top: 20px;

      width: 100px;
      height: 100px;

      background-color: red;
    }
    #fixed {
      position: fixed;

      /* 页面居中*/
      top: 50%;
      right: 50%;
      margin: -50px -50px 0 0 ;

      height: 100px;
      width: 100px;
      background-color: slateblue;

      text-align: center;
    }
  </style>
</head>
<body>
<h2>相对定位</h2>
<div class="container">
  <div class="main"></div>
  <div class="right"></div>
</div>
<h2>绝对定位</h2>
<div class="container2">
  <div class="main2"></div>
</div>
<h2>固定定位</h2>
<p>滚动条查看 固定定位 效果</p>
<div id="fixed">固定定位的小框框</div>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/DurianPudding/article/details/87951317