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

HtmlCssCss Position

Html Problem Overview


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.

Html Solutions


Solution 1 - Html

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, or filter property set to something other than none.

Solution 2 - Html

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

Solution 3 - Html

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

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.

Solution 5 - Html

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTimothy RuhleView Question on Stackoverflow
Solution 1 - HtmlAdrian HolovatyView Answer on Stackoverflow
Solution 2 - Htmltw16View Answer on Stackoverflow
Solution 3 - HtmlliorqView Answer on Stackoverflow
Solution 4 - HtmlMichael.LumleyView Answer on Stackoverflow
Solution 5 - HtmlLimeView Answer on Stackoverflow