Skip to content

Instantly share code, notes, and snippets.

@megclaypool
Last active July 16, 2021 16:14
Show Gist options
  • Save megclaypool/aa064da2ede979469c3f24e8d03637cd to your computer and use it in GitHub Desktop.
Save megclaypool/aa064da2ede979469c3f24e8d03637cd to your computer and use it in GitHub Desktop.
Quickly find the relatively positioned ancestor of an absolute element. Useful if you're trying to figure out which ancestor is the one your absolutely positioned element is positioning relative to...

Original Question:

How can I quickly find the relatively positioned HTML parent element of an absolutely positioned child?

I am working with the following code:

<div>
    <div>
        <div>
            <div>
                <div>
                    <div>
                        ...
                            <div class="absolute">Lorem ispum</div>
                        ...
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

.absolute {
  position: absolute;
}

Using Chrome's DevTools, I'd like to be able to quickly find which parent div element has position: relative, so I can know which parent element is determining the origin point of my absolutely positioned element. I can manually inspect each of the divs to find the first parent that is set to relative but I'm working with a deeply nested tree, so I'm wondering if there is a faster way to find the parent I'm trying to find. A Javascript snippet for the console would be an example of a suitable solution.


How To:

  1. Open the inspector and select the element. In the console, it's now defined as $0.
  2. Switch to console view and type or paste $0.offsetParent;

HTMLElement.offsetParent

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment