Force “position: absolute” to be relative to the document and not the parent container

前端 未结 5 1363
遥遥无期
遥遥无期 2020-12-08 12:34

I am trying to insert a div into any part of the body and make its position: absolute relative to the whole document and not a parent element which has a

相关标签:
5条回答
  • 2020-12-08 13:08

    If you don't want to attach the element to body, the following solution will work.

    I came to this question looking for a solution that would work without attaching the div to the body, because I had a mouseover script that I wanted to run when the mouse was over both the new element and the element that spawned it. As long as you are willing to use jQuery, and inspired by @Liam William's answer:

    var leftOffset = <<VALUE>>;
    var topOffset = <<VALUE>>;
    $(element).css("left", leftOffset - element.offset().left);
    $(element).css("top", topOffset - element.offset().top);
    

    This solution works by subtracting the element's current left and top position (relative to the body) so as to move the element to 0, 0. Placing the element wherever you want relative to the body is then as simple as adding a left and top offset value.

    0 讨论(0)
  • 2020-12-08 13:10

    You will have to place the div outside of the position:relative element and into body.

    0 讨论(0)
  • 2020-12-08 13:17

    You're looking for position: fixed.

    From MDN:

    Fixed positioning is similar to absolute positioning, with the exception that the element's containing block is the viewport. This is often used to create a floating element that stays in the same position even after scrolling the page.

    0 讨论(0)
  • 2020-12-08 13:19

    My solution was to use jQuery for moving the div outside its parent:

    <script>
        jQuery(document).ready(function(){
            jQuery('#loadingouter').appendTo("body");
        });
    </script>
    
    <div id="loadingouter"></div>
    
    0 讨论(0)
  • 2020-12-08 13:28

    This isn't possible with simply CSS and HTML.

    Using Javascript/jQuery you could potentially get the elements jQuery.offset() to the DOM and compare it the jQuery.position() to calculate where it should appear on the page.

    0 讨论(0)
提交回复
热议问题