CSS Positioning: Relative vs Absolute Explained
Q: Can you explain the difference between relative and absolute positioning in CSS and how they are used to position elements on a web page?
- CSS
- Junior level question
Explore all the latest CSS interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create CSS interview for FREE!
In CSS, relative and absolute positioning are used to
position elements on a web page.
Relative positioning is used to position an element relative
to its normal position on the page. When an element is relatively positioned,
it can be moved up, down, left, or right using the top, bottom, left, and right
properties. The element will still take up the same space on the page as it
normally would, so other elements will not be affected by its position.
Absolute positioning, on the other hand, is used to position
an element relative to its nearest positioned ancestor or to the initial
containing block if there is no positioned ancestor. When an element is
absolutely positioned, it is removed from the normal flow of the page, and
other elements will flow around it as if it were not there. The element can be
positioned using the top, bottom, left, and right properties, and its position
is based on its nearest positioned ancestor or the initial containing block.
Here is an example to illustrate the difference between
relative and absolute positioning:
<div style="position: relative;"> <p style="position: absolute; top: 10px; left: 10px;">This is absolutely positioned</p> <p>This is relatively positioned</p> </div>
In this example, the first paragraph is absolutely
positioned and is moved 10 pixels from the top and left edges of its nearest
positioned ancestor, which is the div with relative positioning. The second
paragraph is relatively positioned and is placed in its normal position within
the div.
Overall, relative and absolute positioning are useful tools
in CSS for positioning elements on a web page. Relative positioning is used to
make small adjustments to an element's position, while absolute positioning is
used to position an element precisely and remove it from the normal flow of the
page.


