TL;DR — CSS position indicates the location of elements in an HTML document, whether they follow the normal document flow, or whether they affect other elements.
Contents
How Positions Are Set
static
All HTML elements are static
CSS position by default. It means that elements follow the regular page flow.
Properties of left
, right
, top
, bottom
, z-index
do not affect on static elements.
relative
The CSS position relative
means that an element follows the regular flow of the document, and then offsets relative to itself according to top
, right
, bottom
, left
.
Note: CSS position relative does not affect the location of other HTML elements.
Relative to Itself: What Does That Mean?
The explanation above sounds confusing for beginners. If you set element position to relative
without attributes such as top
and bottom
, the property will not work. The element will simply be static
.
However, if you set the CSS position relative
to top: 30px
, the element position moves 30 pixels to the bottom from its regular position.
fixed
When you set the position fixed
to an element, it is eliminated from the regular flow of the document. Other elements will completely ignore elements that have the position fixed
.
div.fixed {
position: fixed;
left: 5px;
top: 5px;
background-color: green;
}
Note: the fixed position means that an element is relative to the browser window, or the viewport. Therefore, when users scroll, the fixed element remains in its position.
sticky
The CSS position sticky
sets elements as relative
. However, elements become fixed
when the element reaches a specific location during scrolling.
The following example has a sticky header and a sticky footer. They move from the specified position:
header {
position: sticky; top: 30px;
background-color: green;
}
footer {
position: sticky; top: 30px;
background-color: yellow;
}
Note: this CSS position sticky is experimental and does not have the best browser compatibility.
absolute
The absolute
position indicates that an element is eliminated from the regular flow of the document. Other elements ignore the element with the absolute
position.
div.absolute {
position: absolute;
top: 5px;
left: 10px;
height: 50px;
width: 100px;
}
Such elements are relative to the next parent element with relative or absolute position.
Note: the absolute can have top, left, right, bottom.
CSS Position: Useful Tips
- Elements that have the
inherit
position take the position properties from their parents. - Manually setting the static position happens when you need to override other positioning properties.