Force "position: absolute" to be relative to the document and not the parent container
Solution 1:
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.
Notice it doesn't work when...
(...) one of its ancestors has a
transform
,perspective
, orfilter
property set to something other thannone
.
Solution 2:
You will have to place the div
outside of the position:relative
element and into body
.
Solution 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>
Solution 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.