css的定位方式有哪些?

CSS 定位 (Positioning) 属性允许你对元素进行定位。CSS 为定位提供了一些属性,利用这些属性,可以建立列式布局,将布局的一部分与另一部分重叠,还可以完成多年来通常需要使用多个表格才能完成的任务。

css定位的几种方式:

1、static(静态定位):

默认值。没有定位,元素出现在正常的流中(忽略 top, bottom, left, right 或者 z-index 声明)。参考上篇随笔。

2、relative(相对定位):

定位为relative的元素脱离正常的文档流,但其在文档流中的位置依然存在,只是视觉上相对原来的位置有移动。

通过top,bottom,left,right的设置相对于其正常(原先本身)位置进行定位。可通过z-index进行层次分级 。

.static1{
            height:80px;
            background-color: red;
        }
        .relative{
            height:80px;
            position:relative;
            top:40px;
            left:40px;
            background-color: black;
        }
        .static2{
            height:80px;
            background-color: blue;
        }


    </style>
</head>
<body>
    <div class="static1"></div>
    <div class="relative"></div>
    <div class="static2"></div>
</body>

3、absolute(绝对定位):生成绝对定位的元素,相对于 static 定位以外的第一个父元素进行定位。元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。可通过z-index进行层次分级。

定位为absolute的层脱离正常文档流,但与relative的区别是其在正常流中的位置不再存在。

这个属性总是有人给出误导。说当position属性设为absolute后,总是按照浏览器窗口来进行定位的,这其实是错误的。实际上,这是fixed属性的特点。

<style type="text/css">
        .static1{
            height:80px;
            background-color: red;
    
        }
        .father{
            height:100px;
            background-color: pink;
            position:relative;
            left:20px;    
        }
        .relative{
            height:80px;
            width:80px;
            position:absolute;
            top:10px;
            left:10px;
        
            background-color: black;
        }
        .static2{
            height:80px;
            background-color: blue;
        }

    </style>
</head>
<body>
    <div class="static1"></div>
    <div class="father">
        <div class="relative"></div>
    </div>
    <div class="static2"></div>

4、fixed(固定定位):生成绝对定位的元素,相对于浏览器窗口进行定位。元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。可通过z-index进行层次分级。

<style type="text/css">
        .static1{
            height:80px;
            background-color: red;
    
        }
        .father{
            height:100px;
            width:300px;
            background-color: pink;            
            left:100px;    
            top:100px;
        }
        .relative{
            height:80px;
            width:80px;
            position:fixed;
            left:20px;        
            background-color: black;
        }
        .static2{
            height:80px;
            background-color: blue;
        }

    </style>
</head>
<body>
    <div class="static1"></div>
    <div class="father">
        <div class="relative"></div>
    </div>
    <div class="static2"></div>

以上就是css的定位方式有哪些?的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » CSS3 答疑