Query regarding absolute and relative positioning

<style> .pink.box { position: absolute; top: 0px; right: 0px; width: 75px; height: 75px; background: deeppink; } </style> <div class="pink box"></div> <p>Hello World</p> Can anyone help me understand why the absolute positioning works this way where right 0 pushes element to right corner where as relative positioning not doing that?
5 Replies
Chris Bolson
Chris Bolson16mo ago
When using display: relative it positions the element relative to where it would normally be in the flow. So, by setting right: 0 you are setting its position relative to its natural position, regardless of any parent positioning. When using display: absolute you are setting its position relative to its nearest parent with a relative position. So the right: 0 is relative to its parent's position. (I hope I got that right)
Prasanna
Prasanna16mo ago
Thanks Chris for helping. In this case we didn't mention parent position as relative or any positioning right as the div is not contained by anything why it is in same line of hellow world? I still couldn't understand sorry
Chris Bolson
Chris Bolson16mo ago
If you don’t specifically set the position of a parent, position absolute will be relative to the body. That is why it moves off to the far right.
Wouter Schaap
Wouter Schaap16mo ago
@Chris to add to your answer. If you don't set a position on the parent, the absolute positioned child will look for the closest positioned parent element in the dom tree. This isn't always the body tag.
Prasanna
Prasanna16mo ago
Got it Chris on absolute. but why relative is not moving to right with 0 px is been set? You mentioned setting relative to 0 is in natural position is it mean right 0 is already applied or it doesn't apply to relative?
Want results from more Discord servers?
Add your server