Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Absolute div targets parents parent

Tags:

css

position

Simple question, hard answer to find.

So I have 3 div's.

    <div style="position: relative;" class="div-1">

        <div style="position: relative;" class="div-2">

            <div style="position: absolute;" class="div-3">

                Target Div-1's position relative.

            </div>

        </div>

    </div>

The third div is absolute positioned, but it targets the direct parent: div-2. I want it to target div-1. How can I achieve such thing?

like image 399
Don Munter Avatar asked Oct 23 '14 13:10

Don Munter


1 Answers

The MDN's docs on POSITION states:

absolute
Do not leave space for the element. Instead, position it at a specified position relative to its closest positioned ancestor or to the containing block. Absolutely positioned boxes can have margins, they do not collapse with any other margins.

So, the answer is not hard to find... It can't be done in this structure.

The only way would be if the closest positioned element was the first div:

<div style="position: relative;" class="div-1">
    <div class="div-2">
        <div style="position: absolute;" class="div-3">
            Target Div-1's position relative.
        </div>
    </div>
</div>

If you cannot change the HTML, maybe override it with the css class:

.div-2 { position: initial !important; }
like image 165
LcSalazar Avatar answered Oct 16 '22 23:10

LcSalazar