Break an absolutely positioned element out of its

2019-04-14 11: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>