Break an absolutely positioned element out of its relatively positioned ancestor?

早过忘川 提交于 2019-12-06 11:31:55

问题


Suppose I have a document like

<style type="text/css">
div {
  border:1px solid;
  padding:15px;
}

#i_am_relatively_positioned{
  background-color:#fcc;
  margin:50px;
  padding:50px;
  position:relative;
}

#inner {
  background-color:#cfc;
}

#i_want_to_be_absolute_to_body{
  background-color:#ccf;
  left:0;
  position:absolute;
  top:0;
}
</style>

<body>
  <div id="i_am_relatively_positioned">
    <div id="inner">inner</div>
    <div id="i_want_to_be_absolute_to_body">absolute to body</div>
  </div>
</body>

Is there a way to make #i_want_to_be_absolute_to_body positioned absolute with respect to the body element, rather than its immediate relative container?

I know I can just use some negative top and left but that seems kludgey - is this my only option?


回答1:


You can use a bit of javascript to do this (I'm assuming you can't change the markup?).

document.body.appendChild(document.getElementById('i_want_to_be_absolute_to_body'));



回答2:


Is it important, that the Element "i_want_to_be_absolute_to_body" is in the Container "i_am_relatively_positioned"?

If not then this solution:

  <div id="i_am_relatively_positioned">
  <div id="inner">inner</div>
  </div>
  <div id="i_want_to_be_absolute_to_body">absolute to body</div>


来源:https://stackoverflow.com/questions/4865720/break-an-absolutely-positioned-element-out-of-its-relatively-positioned-ancestor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!