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的粘性的效果(能够不随滚动而消失在视口)。