简体   繁体   English

相对于另一个元素而不是其父元素定位元素

[英]Position element relative to another element not its parent

Is it possible to make a positioned element relative to another element which isn't currently its parent?是否可以使定位元素相对于当前不是其父元素的另一个元素? Example:示例:

<div class="want-to-be-parent">
<div class="current-parent">
<div class="element-to-position"><!---content---></div>
</div>
</div>

So in this instance, I want to absolutely position 'element-to-position' at the top left of 'want-to-be-parent' but its currently relatively positioned inside 'current-parent'.所以在这种情况下,我想将“元素到位置”绝对定位在“想要成为父母”的左上角,但它目前相对定位在“当前父母”内。

EDIT - Assume that all three of these elements have 'position: relative' and that I have no control over that.编辑 - 假设所有这三个元素都具有“位置:相对”并且我无法控制它。 I want to absolutely position 'element-to-position' and have it be absolutely positioned relative to 'want-to-be-parent' and not to 'current-parent'.我想绝对定位“元素到位置”,并让它相对于“想要成为父母”而不是“当前父母”进行绝对定位。 I have to do this dynamically as there is no other way.我必须动态执行此操作,因为没有其他方法。

Set want-to-be-parent to position:relative;想要成为父母position:relative; and set current-parent to position:static;并将当前父级设置为position:static;

When you use position:absolute on an element it will position relative to the first parent with non-static position, preferably relative position to avoid messing the layout.当您在元素上使用position:absolute时,它将相对于具有非静态位置的第一个父元素进行定位,最好是相对位置以避免弄乱布局。

Your code should look something like this:您的代码应如下所示:

 .want-to-be-parent { position:relative; padding:40px; border:1px solid; } .current-parent{ padding:40px; border:1px solid; } .element-to-position { position:absolute; top:0; left:0; padding:10px; background:red; }
 <div class="want-to-be-parent"> want to be parent <div class="current-parent"> curent parent <div class="element-to-position"> element </div> </div> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM