Position element relative to another element not its parent
Asked Answered
C

1

7

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.

Cerelly answered 2/7, 2017 at 13:30 Comment(1)
See this past question, related: #33065635Amundsen
W
4

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>
Whitecap answered 2/7, 2017 at 13:33 Comment(4)
Even more interesting when closing the want-to-be-parent immediately, making it a sibling of current-parent. Still works like a charm.Sinecure
Sorry, I wasn't clear. I know how to do this with css, obviously, but I don't want to change anything about those divs or their positioning, I just want to dynamically take the 'element-to-position' from where it is and position it absolutely inside the 'want-to-be-parent'.Cerelly
@Cerelly that is exactly what i have done using css .. i didn't change the html .. maybe you should edit your question to make it more clear :)Whitecap
The nearest positioned ancestor doesn't need to be position: relative. It can be any positioning value except static. Of course, relative makes the most sense since it doesn't disturb the layout.Nicosia

© 2022 - 2024 — McMap. All rights reserved.