开发者

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

开发者 https://www.devze.com 2023-02-07 18:44 出处:网络
Suppose I have a document like <style type=\"text/css\"> div { border:1px solid; padding:15px; } #i_am_relatively_positioned{

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_wa开发者_StackOverflownt_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?


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'));


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消