前面两篇文章为大家详细讲解了相对定位与绝对定位的应用场景和案例。如果想了解的可以在公众号里面查看去看。本小节我们学习下固定定位与粘性定位的应用场景和案例。
![](https://img-blog.csdnimg.cn/img_convert/7708fb32af428404c68b204d98f63a5f.jpeg)
属性值 |
描述 |
relative 相对定位 |
相对于自身正常位置进行位置的调整 |
absolute 绝对定位 |
相对于其最近的定位的父元素进行位置调整。 |
fixed 固定定位 |
相对于浏览器窗口进行位置调整 |
sticky 粘性定位 |
是基于用户的滚动位置来定位。 |
固定定位
相对于浏览器窗口进行定位,其它与绝对定位的特性一致。
常见的应用有:楼梯式导航、浏览器右侧菜单、底部通栏、全屏黑色半透明遮罩弹出层、弹出注册和登录框、左上固定右自适应后台管理系统布局
粘性定位
当滚动的高度>元素与浏览器的高度时,会以fixed固定定位显示。
当滚动高度<元素与浏览器高度时,会以relative相对定位显示。
常见的应用有:吸顶盒导航,滚动吸附效果
1、楼梯式导航、浏览器右侧菜单、底部通栏(固定定位应用)
这三个案例用都是用固定定位来控制其与浏览器位置。最难是楼梯式导航的js部分
<style>
body,ul,li{
margin:0;
padding: 0;
}
.header,.footer{
height: 200px;
background-color: skyblue;
}
.container{
width: 1280px;
margin:20px auto;
}
.container .item:nth-child(odd){
height:600px;
background-color:yellow;
}
.container .item:nth-child(even){
height:700px;/*代码来自-艾编程-清心*/
background-color:darkturquoise;
}
ul.louti{
list-style: none;
width: 100px;
padding:0px 10px;
border: 1px solid #ddd;
border-radius: 10px;
background-color: #fff;
position: fixed;/*通过固定定位来控制楼梯式导航的位置*/
top:300px;
left:50px;
}
ul.louti li{
height: 30px;
line-height: 30px;
text-align: center;
border-bottom:1px solid #ddd;
cursor: pointer;
}
ul.louti li:last-child{
border:none;
}
ul.louti li.current{
background-color: palevioletred;
color:#fff;
}
</style>
<body>
<div class="header"></d