position属性用来定义元素的定位方式。
定位相关属性值
1.static 默认值
2.absolute 绝对定位
3.fixed 固定定位
4.relative 相对定位
5.sticky 粘性定位 (CSS3新增)
定位的作用
1. 在正常情况下,可以让一个元素覆盖在另一个元素上;
2. 需要移动一个元素的位置时,可通过top、right、bottom、left属性来移动元素的位置;
3. 可以固定某个容器在浏览器窗口的某个位置不动;
4. 可以做吸顶效果;
以下就五个属性值展开介绍:
一、position: static; 默认值,无定位
此时 top、right、bottom、left 属性无效。
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title></title> 6 <style type="text/css"> 7 body{margin: 0; padding: 0;} 8 .a1{width: 50px;height: 50px;background: yellow;} 9 .a2{width: 150px;height: 80px;background: skyblue; 10 position: static; 11 } 12 .a3{width: 100px;height: 100px;background: blue;} 13 .a4{width: 80px;height: 150px;background: pink; 14 position: static; 15 } 16 </style> 17 </head> 18 <body> 19 <div class="a1">第一个div</div> 20 <div class="a2">a2第二个div</div> 21 <div class="a3">a3第三个div</div> 22 <div class="a4">a4第四个div</div> 23 </body> 24 </html>
二、position: absolute;绝对定位
1、当一个元素设定为绝对定位后,该元素会脱离文档流。
如果下面的元素没有添加定位,绝对定位的元素会将其覆盖,文字也会被盖住(即全脱离)。
在上面的结构中,给.a2加绝对定位后:
2、层叠顺序
如果多个元素同时给了绝对定位,他们之间的叠层顺序是:结构在后的元素在上面。
给.a2、.a3、.a4加绝对定位后:
如果想要改变定位之后的层叠顺序,可以通过属性 z-index 来改变。z-index的默认值是auto,不带单位、可给负值。数值越大,层越靠上。
.a2、.a3、.a4加绝对定位,同时.a2添加属性 z-index: 1;后:
3、移动位置
定位之后想要移动位置,除了可以使用margin等以外,还可以用left、right、top、bottom作为属性来移动位置。
要注意的是,用left/right/top/bottom来移动时,绝对定位元素的参照物有两种情况:
1>如果其父元素没有定位,那么参照物为浏览器的第一屏;
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title></title> 6 <style type="text/css"> 7 body{margin: 0; padding: 0;} 8 .a1{width: 50px;height: 50px;background: yellow;} 9 .a2{width: 150px;height: 80px;background: skyblue; 10 position: absolute; 11 right: 20px; 12 bottom: 0; 13 } 14 .a3{width: 100px;height: 100px;background: blue;} 15 .a4{width: 80px;height: 150px;background: pink;} 16 .box{ 17 width: 110px; 18 height: 110px; 19 background: green; 20 } 21 </style> 22 </head> 23 <body> 24 <div class="a1">第一个div</div> 25 <div class="box">a2的父元素 26 <div class="a2">a2第二个div</div> 27 </div> 28 <div class="a3">a3第三个div</div> 29 <div class="a4">a4第四个div</div> 30 </body> 31 </html>
2>如果其父元素有定位,参照物为 static 定位以外的第一个父元素。
给.box加定位之后:
三、position: fixed; 固定定位
1、添加固定定位的元素,该元素会固定在某个位置不动,并且会脱离文档流。
2、用left/right/top/bottom移动位置时的参照物,只有一个,是浏览器的当前窗口。
3、层叠顺序:多个元素同时给了固定定位,结构在后的会覆盖在上面。也可使用z-index来改变层叠顺序。
四、position:relative; 相对定位
1、相对定位之后的元素是占浏览器位置的,不脱离文档流。
2、用left/right/top/bottom移动位置时:参照物是自己的初始位置。
移动位置之后,原来的空间还在。
1 <style type="text/css"> 2 body{margin: 0; padding: 0;} 3 .a1{width: 50px;height: 50px;background: yellow;} 4 .a2{width: 150px;height: 80px;background: skyblue; 5 position: relative; 6 left: 40px; 7 bottom: 40px; 8 } 9 .a3{width: 100px;height: 100px;background: blue;} 10 </style>
3、层叠顺序:
多个元素给相对定位之后,如果没有移动位置,那么他们之间就不会有覆盖现象。
如果移动了位置,那么后面的元素还是会覆盖前面的元素。此时,可以用z-index改变层叠顺序。
五、position: sticky; 粘性定位
粘性定位是相对和固定定位的混合体,一般用来实现导航的吸顶效果。
默认情况下,该元素被视为相对定位,直到它超过一定的范围之后,此时它被视为固定定位。
因为sticky为CSS3新增加的属性,对于浏览器存在兼容问题,而JS能更好的实现吸顶效果,这里不再赘述。
原文:https://www.cnblogs.com/uuind/p/12359615.html