position 属性规定元素的定位类型。

  position属性定义建立元素布局所用的定位机制。任何元素都可以定位,绝对或固定元素会生成一个块级框,而不论该元素本身是什么类型。相对定位元素会相对于它在正常流中的默认位置偏移。

定位 = 定位类型(relative,absolute, fixed, static:极少使用)+ 偏移距离(left,right, top,bottom)

 

1. 相对定位 relative: 相对定位不会脱离标准流,保留原来的位置;参照自己原来的位置进行移动

    .relative {
            display: block;
            background: skyblue;
        }
        .r {
            width: 100px;
            height: 100px;
        }
        .r:first-child {
            background: red;
            position: relative;
            top: 50px;
            left: 50px;
        }
        .r:last-child {
            background: blue;
        }

    <div class="relative">
        <div class="r">1</div>
        <div class="r">2</div>
    </div>

 

 

2.绝对定位 absolute:
  如果没有祖先元素或者祖先元素没有定位,则以浏览器为定位参照系(即 Document文档);
  如果祖先元素有定位(relative,absolute,fixed),则以最近一级有定位的祖先元素为参照系移动位置;
  绝对定位脱离标准流,不保留原来位置。
        .father {
            position: relative;
            width: 200px;
            height: 150px;
            background: palegreen;
        }
        .son {
            position: absolute;
            width: 80px;
            height: 80px;
            top: 20px;
            right: 30px;
            background: red;
        }

    <div class="father">
        <div class="son"></div>
    </div>

 

4.固定定位 fixed:

  固定定位 fixed: 让标签固定在浏览器的可视位置。跟父标签没有任何关系;不会随着滚动条滚动.
    .fixed{
        width: 220px;
        height: 100px;
        position: fixed;
        right: 50px;
        bottom: 100px;
        background: red;
    }

 <div class="fixed">position: fixed</div>

 

 

posted on 2020-08-31 15:11  夜之独行者  阅读(69)  评论(0编辑  收藏  举报