CSS position定位属性

css中的position属性是用于设置元素位置的定位方式

它有以下几种取值:

static:默认定位方式,子容器在父容器中按照默认顺序进行摆放

absolute:绝对定位,元素不占据父容器空间,相当于文档body定位,根据父容器的position:relative进行定位,如果父容器没有该属性,就默认以body为父容器进行定位

relative:相对定位,占据父容器空间,但显示位置相当于自身位置进行偏移,可以在父容器上写该属性,帮助子元素定位

fixed:固定定位,元素相当于窗口进行定位(相当于窗口而不是文档定位,所以即使发生进度条滚动时,元素相当于窗口的位置仍然不变)

sticky:粘性定位,这是一个带过渡效果的定位方式,只有在滚动时才能看出其变化效果
当偏移量大于指定值时,以static方式显示
当偏移量小于指定值时,以fixed方式显示,但却像relative方式一样占据父容器空间
当元素到达父容器边缘时,位置相当于父容器不再变化

效果可看以下html代码

1     <body>
2         <div>
3             <div id="div1">div1</div>
4             <div id="div2">div2</div>
5         </div>
6         <div id="div3">div3</div>
7     </body>
8     

默认定位static

 1     <style>
 2         #div1 {
 3              200px;
 4             height: 100px;
 5             background: red;
 6             position: static;
 7         }
 8 
 9         #div2 {
10              200px;
11             height: 100px;
12             background: yellow;
13         }
14 
15         #div3 {
16              200px;
17             height: 100px;
18             background: blue;
19         }
20     </style>

absolute定位

1  #div1 {
2              200px;
3             height: 100px;
4             background: red;
5             position: absolute;
6             left: 400px;
7             top: 300px;

 

relative定位

1         #div1 {
2              200px;
3             height: 100px;
4             background: red;
5             position: relative;
6             left: 400px;
7             top: 300px;
8         }

 fixed定位

1         #div1 {
2              200px;
3             height: 100px;
4             background: red;
5             position: fixed;
6             right: 10px;
7             bottom: 10px;
8         }

 sticky定位

 1     <body>
 2         <div id="div4"></div>
 3         <div id="div1">
 4             <div id="div2"></div>
 5             <div id="div3"></div>
 6         </div>
 7         <div id="div5"></div>
 8     </body>
 9 
10     <style>
11         * {
12             margin: 0px;
13             padding: 0px;
14         }
15 
16         #div1 {
17              400px;
18             height: 400px;
19             background: red;
20         }
21 
22         #div2 {
23              200px;
24             height: 100px;
25             background: yellow;
26             position: sticky;
27             top: 40px;
28         }
29 
30         #div3 {
31              300px;
32             height: 200px;
33             background: rebeccapurple;
34         }
35 
36         #div4 {
37              400px;
38             height: 200px;
39             background: lightblue;
40         }
41 
42         #div5 {
43              400px;
44             height: 2000px;
45             background: lightblue;
46         }
47     </style>
原文地址:https://www.cnblogs.com/qdjj/p/12361167.html