1.代码
元素
<div class="father">
<div class="son">123</div>
</div>
样式
.father{
margin-top: 300px;
width: 100%;
height:100vw;
background-color: aqua;
}
.son{
position: fixed;
background-color: antiquewhite;
width: 200px;
height: 200px;
}
原理:当fixed定位元素未设置top,bottom,left,right定位值时,自动定位到父元素左上角。
效果(1):子元素相对于父元素定位,并且即使父元素非定位元素也起作用。默认位于父元素左上角。
效果(2):当滚动滑动条时,父元素被卷起,但子元素仍距离文档顶部300px,
子元素样式自动改为top:300px;
特性:定位元素的位置只与父元素有关,根据初始时父元素到文档顶部的距离,自动添加top值。