Position element relative to another element not its parent

10,873

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>

Share:
10,873
Jerpl
Author by

Jerpl

Updated on June 29, 2022

Comments

  • Jerpl
    Jerpl almost 2 years

    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.

  • Gerard
    Gerard almost 7 years
    Even more interesting when closing the want-to-be-parent immediately, making it a sibling of current-parent. Still works like a charm.
  • Jerpl
    Jerpl almost 7 years
    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'.
  • Chiller
    Chiller almost 7 years
    @Jerpl 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 :)
  • Michael Benjamin
    Michael Benjamin almost 7 years
    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.