最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Position element relative to another element not its parent - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 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>

发布评论

评论列表(0)

  1. 暂无评论