Force “position: absolute” to be relative to the d

2019-01-23 00:58发布

问题:

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 position: relative.

回答1:

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



回答2:

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.



回答3:

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>


回答4:

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.



回答5:

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.