目录
一、五种定位属性
1、静态定位static
2、相对定位 position: relative;
3、绝对定位 position: absolute;
4、固定定位 position: fixed;
5、粘滞定位 position: sticky;
二、粘滞定位应用案例
1、导航栏
2、返回顶部
一、五种定位属性
1、静态定位static
特点:默认文档流定位
2、相对定位 position: relative;
特点:设置相对定位,相对于自身本身在浏览器中的默认位置,不脱离文档流
配合属性同一方向的属性只能使用一个 top/left/right/bottom
3、绝对定位 position: absolute;
特点:
1.原来位置不保留 脱离文档流
2.默认使用了绝对定位元素无论有无父元素 参照点是body浏览器视口区域
3.如果祖先元素使用了定位属性 则相对于祖先元素定位
top: 20px;
4、固定定位 position: fixed;
设置固定定位
特性:脱离文档流 相对于浏览器视口区域
right: 20px; bottom: 20px;
5、粘滞定位 position: sticky;
特性:特性:不脱离文档流 原先位置保留 relative+fixed定位一个定位属性
默认相对定位达到阈值就是固定定位 设置两个以上的粘滞定位优先设置后加载的一个
top: 0;(设置固定时与顶部的距离)
二、粘滞定位应用案例
1、导航栏
期望效果:侧边导航栏随滚动条滚动到特定位置后就不再移动
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> *{ margin: 0px; padding:0px; list-style: none; } .container{ width: 726px; height: 8000px; background-color: pink; margin:0 auto; } /* 设置导航栏粘滞定位 */ .container ul{ position: sticky; /* 粘滞定位 */ top: 0px; /* top: 40px; */ } /* 设置一级菜单样式 */ .container ul li{ /* 右边框 */ border-right: 1px solid white; width: 120px; height: 50px; /* 文字水平居中 */ text-align: center; /* 文字垂直居中 */ line-height: 50px; font-size: 20px; /* 设置左浮动 导航横向排布 */ float: left; background-color: rgb(120, 120, 203); } .container ul li a{ color: aliceblue; /* 清楚下划线 */ text-decoration: none; } </style> </head> <body> <div class="container"> <div style="height:300px;"></div> <ul> <li><a href="#">首页</a></li> <li><a href="#">亲子旅游</a></li> <li><a href="#">居家生活</a></li> <li><a href="#">宠物生活</a></li> <li><a href="#">美食酒水</a></li> <li><a href="#">个护清洁</a></li> </ul> </div> </body> </html>
复制
效果如图:
图一为图片原始位置,图二为粘滞定位设置top为0px时展示的效果,导航条在到达据顶部0px后就固定不动了,图三为粘滞定位设置top为40px时展示的效果,导航条在到达据顶部40px后就固定不动了。
2、返回顶部
期望效果:滚动条滚动返回顶部图标出现并固定在某个位置,点击按钮回到指定位置,这里返回的是头部
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .head{ width: 1000px; height: 100px; margin: 0px auto; background-color: pink; } .body{ width: 1000px; height: 1000px; margin: 0px auto; background-color: skyblue; } button{ width: 100px; height: 40px; background-color: rgb(92, 92, 97); position: sticky; bottom: 20px; margin-top: 750px; } </style> </head> <body> <div class="head" id="head">顶部</div> <div class="body">体部</div> <button><img src="../images/上箭头.png" alt="上箭头"><a href="#head">返回顶部</a></button> </body> </html>
复制