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.
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.
Share Improve this question edited May 2, 2021 at 12:43 DRosenfeld 1171 silver badge9 bronze badges asked Jul 2, 2017 at 13:30 JerplJerpl 1891 gold badge3 silver badges16 bronze badges 1- See this past question, related: stackoverflow./questions/33065135/… – DRosenfeld Commented May 2, 2021 at 6:48
1 Answer
Reset to default 4Set want-to-be-parent to position:relative;
and set current-parent to 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.
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>