position屬性之fixedcss
fixed老是以body爲定位時的對象,老是根據瀏覽器窗口來進行元素的定位,經過left,right,top,bottom屬性進行定位。html
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style type="text/css"> div{ float: left; margin-right: 20px; } .div1{ background-color: #FF0000; width: 10000px; height: 10000px; } .div2{ background-color: #33FF66; width: 100px; height: 100px; position: fixed; left: 50px; top: 50px; } </style> </head> <body> <div class="div1">層1</div> <div class="div2">層2</div> </body> </html>
在vscode上運行後web
因爲px設置夠大,網頁能夠滾動瀏覽器
在拖動滾動條後,以下圖spa
咱們能夠發現隨着滾動條的下滑,層二的位置始終不變。這即是fixed屬性。3d
若是把層二div中 position:fixed;code
left:50px;htm
top:50px; 而且把層1塊的height設置得大一些(讓頁面有滾動的效果)對象
去掉,那麼,層2將不會隨着滾動條的下滑而下滑,以下圖:blog
sticky
<!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> .container { background: #eee; width: 600px; height: 1000px; margin: 0 auto; } .sticky-box { <!-- position: -webkit-sticky; position: sticky; --> height: 60px; margin-bottom: 30px; background:violet; <!--top: 0px; --> } div { font-size: 30px; text-align: center; color: #fff; line-height: 60px; } </style> </head> <body> <div class="container"> <div class="sticky-box">內容1</div> <div class="sticky-box">內容2</div> <div class="sticky-box">內容3</div> <div class="sticky-box">內容4</div> </div> </body> </html>
上圖html註釋掉 {
position: -webkit-sticky;
position: sticky;
top:0px;
}
運行後,效果以下圖:
能夠看見效果和fixed是同樣的,隨着滾動條移動,圖形也跟着移動。
可是加上
{
position: -webkit-sticky;
position: sticky;
top:0px;
}
以後再運行,效果以下圖:
能夠發現,註釋過的html運行後,內容板塊隨着滾動條的下移消失在視口。而沒有註釋的代碼「內容四」即便在滾動條下滑到最後都停留在視口的最上方。這就是fixed和sticky的屬性的區別了。
再有,由於設置的是top:0px;
讓咱們改爲top:100;運行後以下圖:
能夠看見,滾動條即便下移到最下方,內容板塊也和視口頂部差100px;
sticky實驗總結:
top:0px; 時,屬性和fixed類似。
top: px>0時, 屬性加成relative。
------------------------------------------------------------------------------------------------------------完美分割線----------------------------------------------------------------------------------------------------------------
position:sticky;的生效規則:
一、必須指定top、right、bottom、left四個閾值的其中之一(好比本次sticky使用了top),纔可以使粘性定位生效。
二、到達設定的閾值。
好比本次sticky的閾值爲top:0px;
top:0px;時sticky體現fixed的屬性。
top>0px 時 sticky還要加成relative的屬性。
------------------------------------------------------------------------------------又一完美分割線------------------------------------------------------------------------------------------
sticky和fixed的區別是:
sticky能夠有fixed的滾動的效果,而fixed沒有sticky的粘性的效果(能夠不隨滾動而消失在視口)。