CSS:position——绝对、相对、固定、粘性定位的简单记录

一、相对定位——relative

    有偏移量(left、right、top、bottom)时,元素相对于自身进行偏移,元素不脱离文档流(在原位置还占有空间),不影响其他元素布局

<style>
    #one{
        width: 50px;
        height: 50px;
        background: orangered;
        border: 1px solid #000;
    }
    #two{
        width: 50px;
        height: 50px;
        background: hotpink;
        border: 1px solid #aaaa7f;
        position: relative;
        top: 10px;
        opacity: 0.5;
    }
    #three{
        width: 50px;
        height: 50px;
        background: skyblue;
        border: 1px solid #5c5c5c;
    }
</style>

<body>
    <div id="one"></div>
    <div id="two"></div>
    <div id="three"></div>
</body>

二、绝对定位——absolute

    有祖先元素时,当祖先元素有了任一position(绝对、相对、固定),且子元素设置为绝对定位后,子元素相对于当前的祖先元素进行偏移;子元素会脱离文档流(后面的div会覆盖上来);绝对定位使内联元素支持宽高(块特征),使块元素的默认宽根据内容决定(内联特征)。

<style>
    #father{
        width: 250px;
        height: 200px;
        border: 1px solid #FFD47F;
        position: relative;
    }
    #one{
        width: 50px;
        height: 50px;
        background: orangered;
        border: 1px solid #000;
        position: absolute;
        right: 20px;
        top: 0px;
    }
    #two{
        width: 50px;
        height: 50px;
        background: hotpink;
        border: 1px solid #aaaa7f;
        opacity: 0.5;
    }
    #three{
        width: 50px;
        height: 50px;
        background: skyblue;
        border: 1px solid #5c5c5c;
    }       
</style>

<body>
    <div id="father">
        <div id="one"></div>
        <div id="two"></div>
        <div id="three"></div>
    </div>
</body>

三、固定定位——fixed

使元素脱离文档流,使内联元素支持宽高,使块元素的默认宽根据内容决定;相对于整个浏览器窗口进行偏移,不受浏览器滚动条影响。

fixed

四、粘性定位——sticky

在指定位置,进行粘性操作。

sticky


https://www.bilibili.com/video/BV1gt4y1m7Eo

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。