尝试方案
父元素relative定位,子元素fixed,但是没法直接实现
解决方案
我们想让特定子元素相对于父元素"fixed"定位,也就是说,剩余的子元素不定位。
那我们可以分开来想,如果添加一个祖先元素assistor,有两个祖先元素,一个用于辅助定位,一个用于包裹不定位的内容,这个问题不就解决了吗。像这样👇
child是我们要定位的元素
具体原理:child:{absolute}
的元素会相对于assistor:{relative}的祖先元素进行定位
我们将assistor设置为position: reletive;
,滚动条是在parent中的,这样"fixed"定位和parent内的内容滚动就都实现了。
最终代码
HTML:
<div class="assistor"> <div class="parent"> <div class="child"></div> <div class="placeholder"></div> </div> </div>
CSS:
.assistor { position: relative; /*关键点*/ display: block; width: 500px; height: 300px; margin: 100px auto 0 auto; background-color: #ddd; } .parent { width: 500px; height: 300px; background-color: #888; overflow: auto; /*关键点*/ } .child { position: absolute; /*关键点*/ width: 120px; height: 120px; margin: 100px 50px; background-color: #333; } .placeholder { width: 1000px; height: 1000px; }