I have the following problem: I have a father-div, that's position is "relative". Inside this div I have 2 son-div's. The first son-div should be positioned relative to the father-div. But the second son-div should be positioned to the whole browser-window.
My HTML and CSS:
#father { position:relative; } #son1 { position:absolute; left:0; top:0; } #son2 { position:absolute; left:670; top:140; }
<div id='father'> <div id='son1'></div> <div id='son2'></div> </div>
My problem now is, that the son2-div is also positioned relative to the father-div. Is there any possibility to tell the son2-div, that it should inerhit the "position:relative" of the father and make left and top absolutely absolute to the whole window?
My problem is: I should change this inside a very big, complex HTML-structure, so it's not possible for me to change the HTML-structure.
Note: z-index only works on positioned elements (position: absolute, position: relative, position: fixed, or position: sticky) and flex items (elements that are direct children of display:flex elements).
Chen Hui Jing notes that when you absolutely position a flex item, it's no longer part of the flex layout. Except… it kinda is a little bit. If you make the child position: absolute; but don't apply any top/right/bottom/left properties, then flexbox alignment will still apply to it.
Centering div (vertical/horizontally) Make inner div position absolute and give top and bottom 0. This fills the div to available height. (height equal to body.)
First change
#son2 { position:absolute; left:670; top:140; }
to
#son2 { position: fixed; /*change to fixed*/ left:670px; /*add px units*/ top:140px; /*add px units*/ }
Result:
#father { position:relative; margin: 40px auto; width:200px; height: 200px; background: red } #son1 { position: absolute; left:0; top:0; width:20px; height: 20px; background: black } #son2 { position:fixed; left:70px; top:140px; width:200px; height: 200px; background: green }
<div id='father'> <div id='son1'></div> <div id='son2'></div> </div>
This is unfortunately not possible without changing the HTML structure. An absolute positioned div will always position itself according to its first relative positioned parent.
What you could possibly do however, is change your #father
element's width/height so you can still position your #son2
element correctly. This really depends on your layout and how far you can edit the #father
element without destroying the layout. Or if possible, change your CSS so you do not need position: absolute;
on #son1
(after which you can remove the position: relative;
from your #parent
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With