不修改父级position属性 如何让子元素相对于高层级祖先定位
可行解决方案
以下方案均满足不修改任意父级元素position属性的要求:
方案1:调整DOM结构(成本最低,无后续维护成本)
直接将.Parent0节点从原有层级移动到.Parent3的直接子节点下,调整后DOM结构如下:
<div Class="Parent3"> <div Class="Parent2"> <div Class="Parent1"> </div> </div> <!-- 将Parent0移动到此处 --> <div class="Parent0"> <h1> The element needs to be positioned</h1> </div> </div>
因为.Parent3本身已设置position: relative,不需要修改任何父级属性,.Parent0的绝对定位会直接以.Parent3为基准,添加以下样式即可占满.Parent3:
.Parent0 { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: dimgray; }
方案2:不调整DOM结构,纯CSS适配
如果不能修改DOM结构,由于你现有代码中.Parent2本身是以.Parent3为基准的绝对定位,默认左上角和.Parent3对齐,直接修改.Parent0的样式即可:
.Parent0 { position: absolute; /* 对齐Parent3左上角 */ top: 0; left: 0; /* 直接设置为Parent3的固定尺寸 */ width: 800px; height: 340px; background: dimgray; /* 按需设置z-index保证显示层级 */ z-index: 99; }
如果.Parent2的位置不是默认左上角对齐,只需把top和left设置为对应的负偏移值即可,比如.Parent2相对于.Parent3的left为20px、top为10px,就将.Parent0的left设为-20px、top设为-10px。
方案3:动态适配(适合父级尺寸/位置不固定场景)
如果.Parent3的尺寸是动态的,或者父级位置会发生变化,可以用JS动态计算偏移和尺寸,无需修改任何父级属性,代码如下:
const getEl = selector => document.querySelector(selector) const p3 = getEl('.Parent3') const p2 = getEl('.Parent2') const p0 = getEl('.Parent0') const p3Rect = p3.getBoundingClientRect() const p2Rect = p2.getBoundingClientRect() // 计算Parent2相对于Parent3的偏移 const offsetX = p2Rect.left - p3Rect.left const offsetY = p2Rect.top - p3Rect.top // 动态设置Parent0样式 Object.assign(p0.style, { left: `-${offsetX}px`, top: `-${offsetY}px`, width: `${p3Rect.width}px`, height: `${p3Rect.height}px` })
如果存在页面resize、父级尺寸动态变化的场景,把上述逻辑封装为函数,监听对应事件触发即可。
内容的提问来源于stack exchange,提问作者SEJ
相关产品推荐
相关产品推荐

