6
votes

By default, an HTML element whose position is set to "absolute" will be positioned relative to the browser's viewport.

But if one of the element's ancestors is set to a non-static position, the element will be positioned relative to that ancestor. That ancestor is the element's "offset parent".

The problem: I want to absolute-position an element relative to the viewport, but unfortunately one of its ancestors is relatively positioned, so that has become its offset parent. Since I'm modifying a 3rd-party theme, I can't move the element or remove its ancestor's relative positioning.

Using CSS or JavaScript, is it possible for me to, in effect, set or reset an element's offset parent? I understand that the DOM property [element].offsetParent is read-only, but is there some way to indirectly have the effect of setting it?

3
Can't you use JavaScript to move the element in the hierarchy? - j08691
@j08691That sounds promising +1. I generally understand what you're talking about, but could you post a little more detail in an answer? - Andy Giesler
@j08691Looked into this a little more. Are you talking about something like a jQuery .detach() and then .append()? - Andy Giesler
You can't and anyways it would be kind of bad code to do viewing html as a hierarchal structure. I realize you're working with someone else's template but I would try and get the absolute element higher up the DOM tree. - Poodimizer

3 Answers

4
votes

You could use Javascript to move the element. Here is the jQuery solution with prependTo() function, you could also use appendTo().

http://jsfiddle.net/6557cnew/

$(function() {
    $('.absolute').prependTo('body');
});
.relative {
    position: relative;
    left: 50px;
    top: 50px;
    border: 1px solid blue;
    width: 100px;
    height: 100px;
}
.absolute {
    position: absolute;
    border: 1px solid red;
    left: 0;
    top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div class="relative">
    relative
    <div class="absolute">
        absolute
    </div>
</div>
0
votes

You can use the value of the offset parent to move the child - just calculate the value of the child based on the rendered coordinates of the parent relative to the window.

0
votes

CSS property position: fixed uses the viewport instead of the ancestor. However it's fixed on the screen when scrolling, so this may be an issue.