534 定位常⻅值及原理

http://www.ruanyifeng.com/blog/2019/11/css-position.html




<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>定位常见值及原理</title>
  <style>
    /* 定位的常见的取值:
        区别:
        1.是否脱离正常文档流
        脱离: position: absolute;  position: fixed; (固定不动)
        不脱离: position: relative;

        2.参照物(基点)
        position: relative;  参照物 是自己原本的位置
        position: absolute;  参照物 先看自己的父元素有没有position属性 没有 => 往上进行查找,直到html为止,参照的浏览器窗口   有  =>  参照物: 父元素 (给父元素加一个position)
        position: fixed;     参照物 直接是浏览器窗口(视口)


        相同点: 
        1.都可以和方位属性一起使用 top/bottom/left/right(static除外)
        2.都可以和z-index一起使用(static除外)


        技巧:
        1.为了 方位/z-index起作用 这个时候我们就可以选用相对定位(relative)
        2.需求: 模块固定在浏览器窗口的某个位置(top/bottom/left/right)  可以选用固定定位(fixed)
        3.需求: 给遮盖 + 叠加(icon-play)的容器 可以选用绝对定位 (absolute) => 参照物父元素(position:relative)
      */

    * {
      margin: 0;
      padding: 0;
    }

    div {
      width: 200px;
      height: 200px;
      margin: 20px;
    }

    div:nth-child(1) {
      background-color: gray;
    }

    div:nth-child(2) {
      background-color: green;
    }

    div:nth-child(3) {
      background-color: blueviolet;
    }

    div:nth-child(4) {
      background-color: olive;
    }

    div:nth-child(5) {
      background-color: greenyellow;
    }

    .parent {
      position: relative;
      width: 300px;
      height: 300px;
      background-color: hotpink;
    }

    .static {
      position: static;
    }

    .relative {
      position: relative;
    }

    .absolute {
      position: absolute;
      top: 50px;
    }

    .fixed {
      position: fixed;
      right: 0;
      top: 0;
    }
  </style>
</head>

<body>
  <!-- static默认值 -->
  <div class="static">static默认值</div>

  <!-- relative相对定位 -->
  <div class="relative">relative相对定位</div>

  <!-- absolute绝对定位 -->
  <div class="parent">
    <div class="absolute">absolute绝对定位</div>
  </div>

  <!-- fixed固定定位 -->
  <div class="fixed">fixed固定定位</div>

  <!-- sticky粘连定位 -->
  <div class="sticky">sticky粘连定位</div>

  <div style="height:400px;"></div>
</body>

</html>

posted on 2020-10-07 09:58  冲啊!  阅读(128)  评论(0编辑  收藏  举报

导航