通过本周在逆战班的学习,基本弄懂了CSS3中定位的取值、分类和作用。
首先我们要知道在CSS3中,浮动(float)主要是解决左右排列的问题,而定位(position)主要是解决叠加排列的问题。
定位的取值分为四大类:相对定位(position relative)、绝对定位(position absolute)、固定定位(position fixed)、粘性定位(position sticky)。
相对定位(position relative):不使元素脱离文档流,空间是会被保留的,不影响其他元素的布局。如果没有定位偏移量,对元素本身没有任何影响,如果存在偏移量是根据元素当前位置进行偏移;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> *{margin: 0; padding: 0;} #box1{ width:100px; height:100px; background: red;} #box2{ width:100px; height:100px;background-color: blue; position: relative; left: 10px; top: 10px;} </style> </head> <body> <div id="box1"></div> <div id="box2"></div> </body> </html>
绝对定位(position absolute):使元素完全脱离文档流,让内联元素具备块元素的特性,让块元素支持内联元素的特性。如果绝对定位元素的父容器存在定位,会相对于父容器发生偏移,如果父容器不存在定位,则会相对于整个文档发生偏移;
固定定位(position fixed);和绝对定位比较相似的是使文档脱离文档流,使内联元素具备块元素的特性,使块元素具备内联元素的特性,但是不同的是固定定位(position fixed)是相对于整个浏览器窗口进行偏移的。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .box1{width: 100%; height: 1000px;} .box2{width: 100px; height: 100px;background-color: red; position: fixed;top: 100px; left: 0;} </style> </head> <body> <div class="box1"> <div class="box2"></div> </div> </body> </html>
固定定位是不会改变位置的,浏览器滚动条滑动,其位置也不会改变。
粘性定位(position sticky)的主要作用就是在没有达到指定位置时,是没有定位效果的,到达了指定位置后,就会变成固定定位。
定位的偏移都是由方向left、right、top、bottom加上值组成的,单位为px;例如:left:50px就是向左偏移50个像素,取值可以为负数。
原文:https://www.cnblogs.com/kechong19970316/p/12353193.html