When styling a web page, we are often required to position an element outside the document normal flow, this is where css positioning comes in, css provides an attribute called position, each of its value makes the element behave in different way. In this tutorial we will explore all the css position and how they affect an element.

Static Position

Static is the default position, the element stay within the document flow and doesn't exibit any unusual behaviour. the attributes top, bottom, right and left have no effect on static position.

Relative Position

Relative position alows an element to be positioned relative to its original position.

See the Pen relative position by devspot (@devspot) on CodePen.

In the example above the box is moving 200px to left and 100px down relative to its initial position.

Absolute Position

An element position set to absolute is relative to its closest parent which position is anything but static.

See the Pen absolute position by devspot (@devspot)on CodePen.

In the example above, the green box is relatively positioned to its closest parent (yellow box) which has position set to relative.

Fixed Position

The fixed position is relative to the viewport, since the viewport is fixed, the element will stick at a given position and be completely removed from the document normal flow.

See the Pen fixed position by devspot (@devspot)on CodePen.

On the above example, when you scroll, you will notice, the box staying fixed and not moving along.

Sticky Position

Sticky position allows an element to scroll with the rest of the page until a treshold is reached, then the element become fix and behave like a fixed positioned element.

See the Pen sticky position by devspot (@devspot)on CodePen.

As you can see, the box scroll with the page until it reaches the top and become fix. This is often used to make nav bar stick to top and always accessible without the need to scroll.

This wraps up the short introduction to css positioning, there are still more to learn about this feature, feel free to try yourself to get more familiar with css, and most important, have fun 😀