position定位
1.相对定位 relative
特点:
- 与标准文档流下的盒子没有任何区别
参考点选取:
- 以自身原来位置为参考点
2.绝对定位 absolute
特点:
- 脱离标准文档流
- 层级提高,压盖效果
- 布局方案 (子绝父相)
参考点选取:
-
情况一:父级盒子没有定位
- 单独设置一个盒子为绝对定位,参考点是body盒子为参考
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> .box1,.box2,.box3{ width:100px; height:100px; background-color: orange; } .box2{ /* margin-top:30px; */ background-color: aqua; position:absolute; top:0; left:0 /* 祖先盒子都没有非static的定位设置 */ /* box2 设置绝对定位相对于body */ } .parent{ width:400px; height:400px; border:1px solid red } </style> </head> <body> <div class="parent"> <div class="box1">box1</div> <div class="box2">box2</div> <div class="box3">box3</div> </div> </body> </html> #top:相对body的顶部top位置20px像素处 #left:相对body左边的10像素处 #bottom: #right:
-
情况二:祖先盒子有设置定位,相对于最近的非static祖先元素定位
- 找最近的父级盒子的定位作为参考点
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> .box1,.box2,.box3{ width:100px; height:100px; background-color: orange; } .box2{ /* margin-top:30px; */ background-color: aqua; position:absolute; top:0; left:0 /* */ /* box2 设置绝对定位相对于parent */ } .parent{ /* width:400px; height:400px; */ border:1px solid red; position: relative; } </style> </head> <body> <div class="parent"> <div class="box1">box1</div> <div class="box2">box2</div> <div class="box3">box3</div> </div> </body> </html>
3.固定定位
参考点:固定元素则是相对于浏览器视口本身
4.position的注意事项
注意:子绝父绝,子绝父固,都是以最近的非static父辈元素作为参考点。父绝子绝,子绝父固,没有实战意义,布局网站的时候不会出现父绝子绝。因为绝对定位脱离标准流,影响页面的布局。
父相子绝
:
在我们页面布局中,是常用的布局方案。因为父亲设置相对定位,不脱离标准流,子元素设置绝对定位,仅仅的是在当前父辈元素内调整该元素的位置。