目录
1.4 固定定位(position:fixed)
相对于 视窗 移动,
元素“脱标
.father{
width: 250px;
height: 250px;
background: skyblue;
/* position: relative; */
}
.father .son1{
position: fixed; /*固定定位*/
bottom: 60px; /*从视窗的底部开始向上移动60px的距离*/
left: 50%; /*从视窗的左侧开始向右移动相当于视窗50%宽度的距离*/
width: 50px;
height: 50px;
background-color: pink;
}
.son2{
width: 50px;
height: 50px;
background-color: green;
}
<div class="father">
<div class="son1"></div>
<div class="son2"></div>
</div>
此时,固定定位的元素不会因为页面的上下滑动而改变位置,而仅与视窗的尺寸有关。
1.5 粘性定位(position:sticky)
粘性定位同时具备相对定位和固定定位的特点,当元素未到达指定的位置时,就如同相对定位一样,随着页面的移动而移动,如果元素靠近浏览器视窗边缘一定距离,则粘性定位如同固定定位一样保持静止
如图,自左向右是页面不断下拉的过程,可以看到,粉色子元素与视窗顶部始终保持一个最小10px的间隙,就像是有一面“空气墙”,这就是粘性定位的特点
body{
height: 2000px;
}
.father{
width: 250px;
height: 2500px;
background: skyblue;
}
.father .son1{
position: sticky; /*粘性定位*/
margin-top: 40px;
top: 10px; /*距离视窗顶部的最小距离为10px*/
width: 50px;
height: 50px;
background-color: pink;
}
.son2{
width: 50px;
height: 250px;
background-color: green;
}
<div class="father">
<div class="son1"></div>
<div class="son2"></div>
</div>
另外,粘性定位还具有一些要求:
1、至少要指定top、bottom、left、right中的一项,这项属性就相当于前述的“空气墙”的厚度,如果不设置,粘性定位就同相对定位一样,随着页面的移动而移动,失去了固定定位的部分特点
2、父元素不能设置overflow:hidden或者overflow:auto等属性
3、父元素的高度不能低于粘性定位元素的高度,因为粘性定位的元素是在父对象内部进行移动的,如果没有移动的空间,也就谈不上移动了