Can I bypass the nearest located ancestor?

"An absolutely positioned element is relative to the nearest ancestor located." - MDN: position - CSS

I realized this when there was a parent that was defined as position:relative; but I didn’t understand that position:absolute technically qualified as a “positioned ancestor”.

Here is an example: http://jsfiddle.net/MSzZG/ It would be nice if the text "At the top" could have the top property for the window instead of containing the div , but I just can’t figure out if I can get around.

 <div> <div>Content </div> </div> <div style="position:absolute;"> <div style="position:absolute;top:0px;">At top </div> </div> 

Is there a way around the previously set absolute element (without using a fixed one)? Javascript solution is acceptable.

+6
source share
3 answers

You will need to calculate the difference between its natural position and the desired position in order to place it absolutely in the window.

If you use jQuery, you can let it do the math for you using a function . offset (coordinates) .

+2
source

Answer

No. You cannot do this.

Reasoning

If you could do this, you could position one div completely from the parent. This will not only make the parent “lonely,” but also completely destroy the nesting goals. Nested div tags or any tags in this regard are not just intended for cosmetic purposes; this is done to pass a text value to the user.

May I suggest reconsidering your approach? Perhaps if you explain what you would like the end result to become, we can help you. there must be a solution.

Possible solutions

  • If you want the inner div to be on top, bring it one level up.
  • remove absolute positioning from parent.
  • Using a different positioning method than the absolute.
+2
source

If you want the inner position: absolute div to be positioned relative to the window (which you must specify position: relative on), you do not need to insert it.

position: absolute will ALWAYS be positioned relative to its positioned parent (with position: absolute or position: relative ). You can't get around this - you just need to structure your HTML better or implement CSS differently.

Thus, basically the answer to your question is no :( at least not without using fixed positioning, which you specifically spoke about, not wanting to do.

+1
source

Source: https://habr.com/ru/post/947248/


All Articles