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.
In position: relative , the element is positioned relative to itself. However, an absolutely positioned element is relative to its parent. An element with position: absolute is removed from the normal document flow. It is positioned automatically to the starting point (top-left corner) of its parent element.
To position an element "fixed" relative to a parent element, you want position:absolute on the child element, and any position mode other than the default or static on your parent element. This will position childDiv element 50 pixels left and 20 pixels down relative to parentDiv's position.
An element with relative positioning can overlap other elements without affecting their position or interrupting the normal document flow. Two other things happen when you use relative position on an element: It introduces the use of z-index on that element. This doesn't work with static elements.
We can make the dialog div positioned relative to the parent div by first making it a child of the parent div and then setting the parent position to relative. The parent is set to relative position and the dialog has absolute position. Now the dialog div is rendered over the parent div.
Set 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With