css postion 属性区别【原】

CSS样式中的postion元素有四个属性,即static | absolute | fixed | relative。

static:

默认值。无特殊定位,遵循HTML基本定位规则 。

fixed:

固定定位,参照位置是浏览器窗口的左上角,即坐标点为(0px, 0px);

relative :

对象不可层叠,但将依据 left , right , top , bottom 等属性在正常文档流中偏移位置

absolute:

绝对定位,参展位置是离当前元素最近的定位方式为fixed,absolute,relative的祖先原则的左上角。

将对象从文档流中拖出,使用 left , right , top , bottom 等属性相对于其最接近的一个最有定位设置的父对象进行绝对定位。如果不存在这样的父对象,则依据 body 对象。而其层叠通过 z-index 属性定义。

示例代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<title>fixed和relative和absolute的区别</title>

<style type="text/css">
    body{color:black;}
    #static  {position:static;  left:100px;top:100px;width:100px;  height:100px;  border:1px solid black;}
    #fixed   {position:fixed;   left:100px;top:100px;width:100px;  height:100px;  background:red;}
    #relative{position:relative;left:100px;top:100px;width:900px;  height:900px;  border:1px solid blue;}
    #absolute{position:absolute;left:100px;top:100px;width:100px;  height:100px;  background:yellow;}
</style>
</head>
<body>
    <div id="static">默认static</div>
    <div id="fixed">fixed固定不变</div>

    <div id="relative">relative滚动
        <div id="absolute">absolute滚动</div>
    </div>
    
</body>
</html>

效果图:

其它文章

让div固定在顶部不随滚动条滚动【转】==>https://www.cnblogs.com/whatlonelytear/p/5571251.html

原文地址:https://www.cnblogs.com/whatlonelytear/p/6568114.html