CSS position属性

作者: 潇Lee | 来源:发表于2016-07-28 02:00 被阅读454次

    CSS中 postion 是一个常用的属性,position 有几个属性值:static、relative、absolute、fixed。每个属性都有一定的特点,掌握了这些特点才能正确使用 position 属性。

    1.static

    属性默认值,对象遵循正常文档流,top,bottom,left,right,z-index没有作用。

    2.relative

    相对位置布局,对象遵循正常文档流,占据正常文档流的位置,但是根据top,bottom,left,right参数相对于正常位置相对偏移,就像是你坐火车去上厕所,虽然你离开了你原先的座位,但是你的座位本身还是占据空间的。相对位置布局的元素之间的层叠关系通过z-index属性定义。
    如果设置postion如下:

    position: relative;
    left: 20px;
    top: 20px;
    

    效果如下图:


    relative位置布局

    其中红色虚线是不设置position为relative时的位置,红色实现区域是按上面代码设置position属性值为relative,并且left和top属性都为20px的结果,从上述结果中我们可以看到,偏移是相对其正常文档流中的位置进行偏移的。

    3.absolute

    absolute,意味着“绝对”,可absolute的用法却一点也不“绝对”,还是这个意思,理解的有偏差?不管怎样,absolute的规则是确定的:

    具有absolute属性的块元素,会向上一层一层寻找position不是static的第一个父元素,直到<html>父元素为止,如果存在这样的父元素,left,top,right,bottom所设置的偏移量就是其相对于找到的父元素的偏移量,如果没有,设置的偏移量以浏览器的左上角为基准。

    如下代码中,拥有absolute属性的块元素,其父元素position属性值都是static,按照规则,其相对位置应该是相对于浏览器左上角。

    <style type="text/css">
        html{
            margin: 20px;
            border: solid 1px red;
            position: static;
        }
        body{
            border: solid 1px blue;
            position: static;
            padding: 20px;
        }
        .parent{
            margin: 10px 0px;
            width: 400px;
            height: 300px;
            background-color: pink;
            color: white;
            position: static;
        }
        .child{
            width: 200px;
            height: 60px;
            background-color: #5bc0de;
            color: white;
            position: absolute;
            box-sizing: border-box;
            padding: 20px;
            left: 0px;
            top: 0px;
            box-shadow: 0px 8px 16px rgba(0,0,0,0.18);
        }
    </style>
    
    <body>
    
    <div class="parent">
        parent div
        <div class="child">
            absolute div
        </div>
    </div>
    
    </body>
    

    效果图(红色框代表html区域,蓝色框代表body区域):

    相对浏览器左上角偏移

    如果body属性设置position:relative,会出现什么结果呢?

    相对于body偏移

    所以,你肯定也就知道了,下面这种效果怎么实现了吧


    相对于其他父元素偏移

    上述效果代码:

    .parent{
            margin: 10px 0px;
            width: 400px;
            height: 300px;
            background-color: pink;
            color: white;
            position: relative; /*设置父元素的postion值为非static*/
        }
        .child{
            width: 200px;
            height: 60px;
            background-color: #5bc0de;
            color: white;
            position: absolute;
            box-sizing: border-box;
            padding: 20px;
            left: 400px; /*设置偏移距离*/
            top: 0px;
            box-shadow: 0px 8px 16px rgba(0,0,0,0.18);
        }
    

    4.fixed

    fixed很简单,脱离文档流,相对浏览器窗口定位,即使页面内容滚动,fixed区域位置不会跟着变动。z-index确定层叠关系。

    参考博客:CSS中position属性( absolute | relative | static | fixed )详解

    相关文章

      网友评论

        本文标题:CSS position属性

        本文链接:https://www.haomeiwen.com/subject/ictajttx.html