Break an absolutely positioned element out of its

2019-04-14 11:58发布

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?

2条回答
做自己的国王
2楼-- · 2019-04-14 12:16

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>
查看更多
迷人小祖宗
3楼-- · 2019-04-14 12:35

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'));
查看更多
登录 后发表回答