简体   繁体   中英

Relatively Positioned Elements and Absolutely Positioned Elements

Relatively positioned elements and absolutely positioned elements work hand in hand, right?

An absolutely positioned element is relative to the closest parent element that is relatively positioned, and if there is no relatively positioned element, by default, the absolutely positioned element is relative to the browser viewport, right?

If this is true, if the closest relatively positioned parent elements are above and below the parent of the absolutely positioned element which one would the absolutely positioned element be relative to?

see, an absolute element will always listen to his nearest relative positioned parent if its inside of it ,

<div relative 1> <div relative 2> <div absolute></div> </div></div>

the absolute div will listen to relative 2, not matters what.

A parent element is per definition always above. There is only one closest parent for each element: <parent><child/><child/></parent> .

 main { display: flex; flex-flow: row wrap; background-color: #00BCD4; padding-bottom: 3rem; } section { box-shadow: 0 0 20px black; min-height: 200px; flex: 1 0 200px; box-shadow: inset 0 0 20px 0px #ccc; background-color: #eee; border: 1px solid #aaa; margin: 3rem; } section > div { background-color: #E91E63; width: 40px; height: 40px; } h3 { color: #FFF; margin: 1rem 3rem 1.5rem 1rem; font-family: sans-serif; font-size: 2.5rem; } .relative { position: relative; } .absolute { position: absolute; } .tr { top: 0; right: 0; } .br { bottom: 0; right: 0; } .bl { bottom: 0; left: 0; } 
 <main class="relative"> <h3 class="absolute br">Child of main</h3> <section class="relative"> <div class="absolute"> </div> <div class="absolute tr"> </div> <div class="absolute br"> </div> <div class="absolute bl"> </div> </section> <section class="relative"> <div class="absolute"></div> <div class="absolute tr"> </div> <div class="absolute br"> </div> <div class="absolute bl"> </div> </section> </main> 

"Elements that are relatively positioned remain in the normal flow of the document. In contrast, an element that is absolutely positioned is taken out of the flow; thus, other elements are positioned as if it did not exist. The absolutely positioned element is positioned relative to its nearest positioned ancestor (ie, the nearest ancestor that is not static). If a positioned ancestor doesn't exist, it is positioned relative to the ICB (initial containing block), which the containing block of the document's root element." - https://developer.mozilla.org/en-US/docs/Web/CSS/position

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