如何让div在另一个div内浮动?fixed定位失效问题求助
解决fixed定位元素超出父容器并被后续元素覆盖的问题
问题原因
position: fixed的元素是相对于浏览器视口定位的,完全脱离文档流,不受父容器.container的约束,因此会超出Div1的范围- 元素被Div2覆盖是因为默认堆叠层级相同,后续元素在文档流中位置靠后,会显示在上方
解决方案
将元素的定位方式改为position: absolute,利用父容器已设置的position: relative实现相对父容器定位,同时调整堆叠层级避免被覆盖:
修改后的CSS代码
.wrapper { width:100%; height: 200px; overflow-y: scroll; } .container { width: 301px; margin: 0px auto; height: 1501px; background: green; position: relative; z-index: 1; /* 确保Div1容器层级高于Div2 */ } .element { background:yellow; position:absolute; /* 改为相对父容器定位 */ width:101px; height:71px; top:51px; right:0px; /* 相对于父容器右侧对齐,而非视口 */ border:2px solid blue; z-index: 2; /* 确保元素在Div1内容上方 */ }
对应的HTML代码(无需修改)
<div class="wrapper"> <div class="container"> Div 1 <div class="element">Div to float</div> </div> </div> <div class="container" style="margin-top: 30px; background: purple">Div 2</div>
修改说明
- 用
absolute替换fixed:让元素相对于设置了relative的父容器.container定位,不再脱离父容器范围 - 移除硬编码的
left:769px:改用right:0px实现相对于父容器右侧的对齐,适配父容器的宽度 - 添加
z-index:给Div1的容器设置z-index:1,给浮动元素设置z-index:2,确保元素不会被Div2覆盖
内容的提问来源于stack exchange,提问作者Varun
相关产品推荐
相关产品推荐

