The CSS position property is very handy when it comes to positioning elements on the page. It might be a bit confusing at first, but it’s definitely worth digging into. Sure flex and grid will dominate most uses, but from time to time you will need a good old position property to achieve just what you have imagined.
There are five different positions that can be used: static, relative, absolute, fixed, and sticky. Let’s dive into each of them.
Static is the default position that all the elements have unless we state otherwise. It follows the document flow and left, right, top, bottom, and z-index properties have no effect on it.
The relative position allows us to offset an element in relation to its original place in the document. We can use the top, bottom, left, and right properties to guide it. The relatively located element does not affect the positioning of other elements around it.
Similarly to the relative option, the absolute position allows us to place an element with the help of left, right, top, and bottom. But, the difference is that the absolute position is determined in comparison to the positioned ancestor element (the first ancestor that has a declared position). If there’s no such ancestor then it’s placed in connection to the initial containing element. (like the HTML document) Another important differentiation from the relative is that the element is removed from the normal document flow.
Fixed, as the name states, provides a fixed position that stays the same even when we move around the page (for example if we scroll). It also works in regard to the HTML document, and not the ancestors (in difference to absolute that looks at positioned ancestors first).
Sticky is a combination of relative and fixed. I would put it like this – it provides the relative placement until the sticky one is needed. So an element has its usual position in the document flow until we start scrolling and then it becomes sticky (sticks to its fixed positioning).
If you want to play around and test different positions you can easily do that here with their ‘Try it yourself’ option.