css position 属性 (absolute 和fixed 区别)

在css3中,position的属性值有:inherit, static, relative ,absolute, fixed.

inherit 是继承父元素的position属性值,IE不支持。

static 默认值,元素出现在正常的流中,忽略 (TRBL)和z-index的值。请参照下面的例子,div1由于position的值为static,所以top,left 没有起作用.

<!Doctype html>
<meta charset="utf-8">
<head>
<title>test position static</title>
    <style type="text/css">

        .divPos{
            position:static;
            left:100px;
            top:100px;
        }
    </style>

</head>
<body>
<div class="divPos">this id div 1(position is static)</div>
<div class="div2">this is div 2</div>
</body>
View Code

  inherit 和 static差别:在运行过程中,position 如果为static则始终保持不变,如果为inherit则可在运行过程中改变。

relative相对定位,相对于正常文档流的正常位置进行定位。如下面的例子中,一个div 相对于正常位置 偏移100px. 这里有点需要注意,positino设置relative 之后,元素仍保留未定位前的形状,它所占用的空间会保留。就是说,未定位以前,div默认是块级元素(div默认属性),定位之后依然是块级元素。

<!Doctype html>
<meta charset="utf-8">
<head>
<title>test position static</title>
    <style type="text/css">
        body{
            background-color:#ffff33;
        }
        .divPos{
            position:relative;
            left:100px;
            top:100px;
            background-color:#000fff;
        }
    </style>
</head>
<body>
<div class="divPos">
    The position of this div is relative...
</div>
</body>
View Code

absolute 生成绝对定位的元素,相对于static以外的第一个父元素进行定位。如下面的例子所示,

<!Doctype html>
<meta charset="utf-8">
<head>
<title>test position static</title>
    <style type="text/css">
        div{
            background-color:#33ff33;
        }
        .divPos{
            position:absolute;
            left:50px;
            top:50px;
        }
        .div3{
            position:absolute;
            left:50px;
            top:50px;
        }
    </style>

</head>
<body>
<div class="divPos">div parent
    <div>
    <div class="div3">div child 3</div>
    </div>
</div>
</body>
View Code

fixed生成绝对定位的元素,相对于浏览器窗口进行定位。如下面的例子,可以滚动右边的滚动条,div 相对于窗口始终在相同的位置。其实,更恰当的例子,是做个购物车。

<!Doctype html>
<meta charset="utf-8">
<head>
<title>test position static</title>
    <style type="text/css">
        .divPos{
            position:fixed;
            left:50px;
            top:50px;
        }
        .div1{
            height:1000px;
        }
    </style>

</head>
<body>
<div class="divPos">
    The position of this div is fixed.And this div will be always here.
</div>
<div class="div1"></div>
</body>
View Code
原文地址:https://www.cnblogs.com/bg57/p/4446805.html