What is the difference between absolute, relative, fixed, and sticky positioning in CSS?
5318-Oct-2024
Updated on 18-Oct-2024
Home / DeveloperSection / Interviews / What is the difference between absolute, relative, fixed, and sticky positioning in CSS?
Ashutosh Kumar Verma
18-Oct-2024Relative positioning
With
position: relative;
, the element is positioned relative to its normal position in the document flow. This allows you to offset the element from its original position without affecting other elements. However, the space it originally occupied is still preserved.Absolute positioning
position: absolute;
removes the element from the document flow, which means it no longer affects the layout of other elements. It is positioned relative to its closest positioned ancestor (an element with aposition
other thanstatic
). If there is no positioned ancestor, it will be positioned relative to the<html>
element.Fixed positioning
position: fixed;
also removes the element from the document flow, but unlike absolute positioning, it is always positioned relative to the viewport (browser window). It remains fixed in its place even when the page is scrolled.Sticky positioning
position: sticky;
lets the element behave likerelative
until the user scrolls to a certain point, after which it behaves likefixed
. When the element reaches a determined scroll position (set usingtop
,right
,bottom
, orleft
) it "sticks" in its place.