css四种定位

浮动和定位的分别:

浮动目的是多个块级元素一行显示

定位主要是移动位置,让盒子移动到想要的位置上去

 

一、position:static

静态定位:对于边偏移无效的(left,top属性无效),一般用来清除定位,一个原来有定位的盒子,不想加定位了,就用这个

二、position:relative

相对定位:不脱离标准流,是相对盒子元素原有的位置进行偏移,设定垂直方向和水平方向,left,top,rigit,bottom,不会对其他元素产生影响

三、position:relative

相对定位:不脱离标准流,是相对盒子元素原有的位置进行偏移,设定垂直方向和水平方向,left,top,rigit,bottom,不会对其他元素产生影响,原来的位置继续占有

四、position:absolute

绝对定位:脱离标准流,如果父亲没有定位,以浏览器为基准进行定位;

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="utf-8" />
 5     <style type="text/css">
 6         .father {
 7             width: 300px;
 8             height: 300px;
 9             background-color: pink;
10             margin: 100px;
11         }
12 
13         .son {
14             width: 100px;
15             height: 100px;
16             background-color: purple;
17             position: absolute;
18             top: 15px;
19             left: 15px;
20         }
21     </style>
22     <title></title>
23 </head>
24 <body>
25     <div class="father">
26         <div class="son">孩子跑走了</div>
27     </div>
28 
29 </body>
30 </html>

父亲有定位,以父亲为基准定位,一种relative,也可以是absolute;

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="utf-8" />
 5     <style type="text/css">
 6         .father {
 7             width: 300px;
 8             height: 300px;
 9             background-color: pink;
10             margin: 100px;
11             position: relative;/*父亲有定位*/
12         }
13 
14         .son {
15             width: 100px;
16             height: 100px;
17             background-color: purple;
18             position: absolute;
19             top: 15px;
20             left: 15px;
21         }
22     </style>
23     <title></title>
24 </head>
25 <body>
26     <div class="father">
27         <div class="son">孩子跑走了</div>
28     </div>
29 
30 </body>
31 </html>

应用:

子绝父相

1.相对定位 占有位置 不脱标

2.绝对定位  不占有位置  完全脱标

应用图片滚动

五、position:fixed

固定定位:fixed定位的参照物总是当前的文档。利用fixed定位,我们很容易让一个div定位在浏览器文档的左上,右上等方位。

代码改变世界~
原文地址:https://www.cnblogs.com/hxiaoman/p/14840062.html