CSS Positioning
The "position" property in CSS specifies the type of positioning method used for an element.
There are five different position values:
- static
- relative
- fixed
- absolute
- sticky
Elements are then positioned using the top, bottom, left, and right properties.
Static and Relative Positioning
The default positioning mode that you’ve gotten used to is position: static. The difference between static and relative is fairly simple. Static is the default position of every element, and properties top, right, bottom, and left do not affect the position of the element. Relative on the other hand is pretty much the same as static, but properties top, ri....(etc.) displace the element relative to its normal position in the flow of the document. Other content will not be adjusted to fit into any gap left by the element.
Absolute Positioning
Using position: absolute on an element will remove that element from the normal document flow while being positioned relative to an ancestor element. However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling. This property is really useful when you want to position something at an exact point on the screen, without disturbing any of the other elements.
Disclaimer: absolute positioning has very specific use cases and if possible, using flexbox or grid should be prioritized. Absolute positioning shouldn’t be used to do entire page layouts.
Fixed Positioning
Fixed elements are also removed from the normal flow of the document and are positioned relative to the viewport and stay there as the user scrolls. This is especially useful for things like navigation bars and floating chat buttons.
Sticky Positioning
Sticky elements will act like normal elements until you scroll past them, then they start behaving like fixed elements. They are also not taken out of the normal flow of the document.