简体   繁体   中英

Why is an absolutely positioned element placed by its sibling instead of at the top corner of the page?

I don't understand why my absolutely positioned element appears after my child_static div. I always thought that absolutely positioned elements are taken out of the flow. So why doesn't child_absolute cover the child_static div?

 .parent { position: relative; } .child_static { height: 20px; background: blue; } .child_absolute { position: absolute; height: 20px; width: 100%; background: green; } 
 <div class='parent'> <div class='child_static'></div> <div class='child_absolute'></div> </div> 

http://jsfiddle.net/4v4eLtp1/

I always thought that absolute positioned elements are out of the flow.

Yes, they are removed from normal flow.

I don't understand why absolute positioned element appeared after child_static div.

Just because absolute positioning removes elements from normal flow, it doesn't mean it does alter the position of the elements as well.

In other words, absolutely positioned elements would be at the same place as they are not positioned absolutely unless their top , left , ... offsets are set.

So what happens is that they would overlap next sibling elements, because they are not part of document flow anymore.

For instance have a look at the following example where the gold <div> element is covered by absolute ly positioned element.

 .parent { position: relative; } .child_static { height: 20px; background: blue; } .child_absolute { position: absolute; height: 20px; width: 100%; background: green; } .child_static ~ .child_static { background: gold; } 
 <div class='parent'> <div class='child_static'>Green</div> <div class='child_absolute'>Blue</div> <div class='child_static'>Gold</div> </div> 

You forgot to set from which sides your DIV is positioned.

Something like:

top: 0;
left: 0;

http://jsfiddle.net/Paf_Sebastien/uqprmkwo/

(I changed the 2nd DIV dimensions so you can see both.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM