The CSS position properties effectively specify the type of positioning method used for an element.
CSS Position properties
Below is the syntax for adding position:
Selector {
position: value;
}
The selector can be any one or more of those discussed previously in CSS Selectors.
" position" is the property key
" value" can be in static, sticky, relative, fixed or absolute.
Playground Example: To make things simpler, you can click the button below to open the playground, which comes with pre-filled HTML and CSS.
In the editor, you will see HTML, CSS, and JS input on the left/top, and the output on the right/bottom.
CSS static position
An element with a static position is always positioned according to the normal flow of the page.
.static {
position: static;
}
An element with a static position remains unaffected by the top, bottom, left, and right properties.
CSS relative position
An element with a relative position is always positioned relative to its normal position.
Here is the syntax for setting the relative position:
.relative {
position: relative;
left: value;
right: value;
top: value;
bottom: value;
}
Relative positions are used to adjust an element's position from its normal position by setting the top, right, bottom, and left properties.
Note: All four properties (top, right, bottom, and left) are not mandatory.
CSS fixed position
An element with a fixed position is always positioned relative to the viewport.
Here is the syntax for setting the fixed position:
.fixed {
position: fixed;
left: value;
right: value;
top: value;
bottom: value;
}
Fixed positions are used to adjust an element's position relative to the viewport by setting the top, right, bottom, and left properties.
Fixed elements always stay in the same place, even when the page is scrolled.
Note: All four properties (top, right, bottom, and left) are not mandatory.
Try to scroll and observe that the fixed element maintains its position.
CSS sticky position
An element with a sticky position alternates between relative and fixed, depending on the scrolling position.
.sticky {
position: sticky;
left: value;
right: value;
top: value;
bottom: value;
}
By default, an element with a sticky position maintains a relative position until its offset is reached.
CSS absolute position
An element with an absolute position is always positioned relative to the nearest positioned parent element.
Here is the syntax for setting the absolute position:
.absolute {
position: absolute;
left: value;
right: value;
top: value;
bottom: value;
}
Absolute vs Fixed
Fixed elements are positioned relative to the viewport, while absolute elements are positioned relative to the nearest positioned parent element.
Fixed elements always remain in the same place, even when the page is scrolled. However, absolute elements scroll with the page.
Want to practice more? Click here for more hands-on exercise.
References: