简体   繁体   中英

CSS position relative and absolute

I am new to web development. I have some doubt related to positioning of elements.

When i run the below code the black background element is inside the red background element.

 <!DOCTYPE html> <html> <head> <title></title> </head> <body> <div style="position: absolute;left:100px;top: 100px;height:600px;background-color: yellow;width: 600px;"> <div style="position:relative;left:100px;top:100px;height:200px;width:500px;background-color: red;"> </div> <div style="position:relative;left:100px;top:50px;height:10px;width:10px;background-color: black;"> </div> </div> </body> </html> 

But if I make position of red rectangle to be absolute then black rectangle moves to the correct positioning maintaining the correct left and top from its parent(yellow rectangle). Can anyone tell me why is it like that? How can I make the black rectangle to correctly position itself from its parent(yellow rectangle) even if the position of red rectangle is relative.

Thanks

relative positioning keeps elements on the page so their position is affected by other static and relative positioned elements. If you want the black box to be positioned relative to the yellow box, you want to make the black box position: absolute . An absolute ly positioned element will be positioned relative to it's closest non- static positioned ancestor.

 <!DOCTYPE html> <html> <head> <title></title> </head> <body> <div style="position: absolute;left:100px;top: 100px;height:600px;background-color: yellow;width: 600px;"> <div style="position:relative;left:100px;top:100px;height:200px;width:500px;background-color: red;"> </div> <div style="position:absolute;left:100px;top:50px;height:10px;width:10px;background-color: black;"> </div> </div> </body> </html> 

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