CSS如何正确定位搜索菜单 使fixed属性子元素跟随父div滚动
问题原因
position: fixed 定位的元素是直接相对于浏览器视口固定的,不受任何父元素滚动行为影响,所以才会出现滚动外层.main时,.inner不跟随.outer移动的问题。
解决方案
将.inner的定位属性从fixed改为sticky,同时添加top: 0指定吸附位置即可,其他原有代码不需要改动。
sticky定位的特性是:仅相对于最近的带滚动属性的祖先元素(也就是你这里设置了overflow: scroll的.outer)生效,滚动.outer时.inner会吸附在.outer顶部固定,滚动.main时整个.outer整体移动,.inner自然就会跟随.outer一起滚动,完全符合需求。
修改后的完整CSS代码
.main{ width:600px; height: 700px; border:1px solid black; position:relative; } .outer{ width:500px; height: 500px; border:1px solid black; position:relative; overflow:scroll; } .inner{ width:400px; height: 40px; border:1px solid black; /* 替换原fixed定位为sticky */ position: sticky; top: 0; background: #fff; /* 可选,避免滚动时下方内容透上来 */ } .content{ margin-top:45px; height:600px; border:1px solid red; width:100px }
内容的提问来源于stack exchange,提问作者Mohammed Mak
相关产品推荐
相关产品推荐

