CSS之position
在我們學習css中佈局常用到的position,position的含義是指定位型別,取值型別可以有:static、relative、absolute、fixed、inherit和sticky,今天主要是說一下static、relative、absolute、fixed四個的作用和用法。在學習這些之前,我們需要知道標準文件流的概念
標準文件流:標準文件流指在不使用其他與排列和定位相關的特殊CSS規則時,元素的預設排列規則,說白了就是沒做改變的頁面元素。
一 、static(靜態定位)
這是position的預設值,表示沒有定位。這個沒有什麼好說的。
二、absolute(絕對定位)
表示採用絕對定位方式,相對於position值不是static的父容器進行定位,該值會使元素脫離文件流,使用該值後可以用left,right,top,bottom
<!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> .relative{ width: 400px; height: 300px; background-color: pink; position: relative; } .static{ width: 300px; height: 200px; background-color: green; border: 5px solid #000; margin:auto; } .absolute{ position:absolute; left: 10px; top:0; width: 200px; height: 200px; background-color: skyblue; } </style> </head> <body> <div class="relative"> <div class="static"> <div class="absolute"></div> </div> </div> </body> </html>
結果:
這裡要知道的是body的預設屬性position不為static,因為當relative盒子父親不為static時候,其會相對於body來進行定位
三、relative(相對定位)
表示採用相對定位的方式,相對於元素原本的位置進行定位,該值不會使元素脫離文件流,使用該值後可以用left,right,top,bottom
對元素進行移動定位
在這裡我們需要知道在relative相對移動後,其實是相對於自己移動了,是視覺上的移動,其實其仍然佔有原來的文件流中的位置。
下面我們就來看一下:
程式碼: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> .father{ margin: 50px 0 0 50px; } .re1{position:relative;
width: 150px; height: 150px; background-color: pink; } .re2{
position:relative; width: 150px; height: 150px; background-color: skyblue; } </style> </head> <body> <div class="father"> <div class="re1"></div> <div class="re2"></div> </div> </body> </html>
結果:
現在我們加上屬性:
.re1{ position: relative; bottom: 20px; width: 150px; height: 150px; background-color: pink; }
結果:
可以看出relative在移動後還是還是佔有原來的文件流中的位置
注意:absolute定位後,其已經不佔有原來的位置,我們把剛才那個relative定位改成absolute定位
.re1{ position: absolute; top: 20px; width: 150px; height: 150px; background-color: pink; }
可以看出已經不佔有位置了,skyblue這個div已經移動上去了,其實可以想想浮動的時候也是類似。
四、fixed
表示採用固定定位的方式,相對於瀏覽器視窗進行定位,並且無論滾動條怎麼滾動,使用了該值的元素都始終處於固定位置,該值會使元素脫離文件流,使用該值後可以用left,right,top,bottom
對元素進行移動定位
上程式碼:
<!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> *{ padding: 0; margin: 0; } .father{ width: 100%; height: 5000px; background-color: pink; } .fix{ position:fixed; right: 0; } </style> </head> <body> <div class="father"> <div class="fix"> <img src="https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2513539719,1581894780&fm=26&gp=0.jpg" alt=""> </div> </div> </body> </html>
結果:
可以看出當滑鼠下滑時圖片也是固定不動的;