Skip to main content

Difference between relative positioning and absolute positioning in CSS

 


Difference between Relative position and Absolute position in CSS

If you are having difficulty understanding the difference between relative positioning and Absolute positioning in CSS, then this will help you understand it better. Let's dive in using practical example.

All CSS element are in static position based on its current position in the flow unless we change its position. The top, right, bottom, left and z-index properties do not apply.

Now

Let's  create three boxes with html and CSS using the code below


Result:




                Relative positioning

Relative positioning places an element relative to its current position without changing the layout around it.

Applying relative positioning on the code


Result:



It move the green box relative to its current position to 20px from the left and top without changing the layout around it. Thus, leaving a gap for the green box where it would have been had it not been position.



                   Absolute positioning

Absolute positioning places an element relative to its parent’s position and changing the layout around it.

Applying absolute positioning on the code

Result:




it will not leave any gap where it would have been. The position of the GreenBox is based on its parent position (the dotted border). Thus, moving 20px to the left and bottom from the top-left origin of the dotted border.


Thanks for reading

@gabrielogbu

#webdev

Comments

Post a Comment