question about css position: absolute | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

question about css position: absolute

https://code.sololearn.com/W21wQCbg236p/#css in this code, blue square is underneath the red square, 100% overlapped. Blue one is position:absolute, red one is position:relative. Why this happened? I didn't write anything about margins... https://code.sololearn.com/WdqR4QKmdT3i/#html In this code, I changed the blue square's position to relative. This time the squares are not overlapping. (both divs are positioned relative.) I learned that " An element with position: absolute; is positioned relative to the nearest positioned ancestor " The 'ancestor', what does it actually mean? It doesn't have to be parent-child relationship? Can it be just placed next to each other like this? <div class="blue">Blue</div> <div class="red">Red</div> Div class="blue" is written ""before"" div class="red" but the blue one's position(absolute) gets affect from the red one(relative) ?

29th Mar 2020, 5:48 PM
Goomba_duu
Goomba_duu - avatar
3 Answers
+ 3
Just remember that relative positioned element keeps absolute childrens inside them. Absolute element can be positioned without getting affected by other elements. Element with a position you can use z-index to determine which element is on top of what
29th Mar 2020, 7:00 PM
Toni Isotalo
Toni Isotalo - avatar
0
I didn't know exactly what ancestor element is, so I looked it up (http://www.littlewebhut.com/css/info_element_relationships/) <body> <h1>This is a sample h1 heading</h1> <div> <h2>This is a sample h2 heading</h2> <p>This is sample text.</p> <div> </body> Ancestor Element - An element that contains (at any level) other elements is an ancestor of the elements that it contains. - In the example above, the <body> element contains (at some level) the <h1>, <div>, <h2> and <p> elements. Therefore, the <body> element is an ancestor of all 4 of these elements. - In the example above, the <div> element contains the <h2> and <p> elements. Therefore, the <div> element is an ancestor of the <h2> and <p> elements. Since the <div> element directly contains the <h2> and <p> elements, the <div> element is also the parent of the <h2> and <p> elements. so the absolutely positioned element should be nested inside of the ancestor element in order to be positioned relatively.
29th Mar 2020, 8:21 PM
Goomba_duu
Goomba_duu - avatar
0
Also, "absolutely positioned elements are removed from the document flow" so in the first code red square takes up the place of the blue one, so they are overlapped. I reviewed what I've learned and I found out why I was confused.
29th Mar 2020, 9:07 PM
Goomba_duu
Goomba_duu - avatar