Confused about CSS positions? Read this and find out!

A detailed guide to CSS positions

·

2 min read

Confused about CSS positions? Read this and find out!

If you've done any web development before, you're probably familiar with HTML elements having positioning values like absolute and relative. These tell the browser how to display an element on the page, for example, by moving it around from the document flow or hiding it from view entirely. But what do these positioning values mean? How do CSS positions work? And how do they interact with each other to achieve specific desired effects? Let's explore!

Static Position

All the elements in HTML are positioned static by default. A static positioned element is an element that has no special positioning applied to it, and it is the default position for every element. It is always positioned according to the normal flow of the page.

Fixed Position

A fixed position element is positioned relative to the viewport or the browser window itself. The viewport doesn't change when the window is scrolled, so a fixed positioned element will stay right where it is when the page is scrolled. Position fixed takes the element out of the screen, and the coordinate system is bound to the screen, and the element sticks to it. It is often used for navigation elements and can also be good for things like a logo or advertisement that you want to stay in one spot on a page no matter how far someone scrolls.

Relative Position

If you use the position property in CSS with a relative value, you tell the element to move relative to where it would generally be on the page. This element is positioned relative to its normal position.

Absolute Position

Absolute positioning takes an element out of the flow of the page so that other elements are positioned as if that element didn't exist; Absolute positioned elements are removed from the normal flow and can overlap elements. Usecase occurs when the element has absolute value and has a relative parent. The element position absolute uses the relative position element as a coordinate system. Position absolute takes the element out of the regular Html coordinate system and puts it to the nearest relative parent. However, if an absolute positioned element has no positioned ancestors, it moves with the document body and changes when you scroll.

Sticky Position

Sticky positioning is a hybrid of relative and fixed positioning. An element with a sticky position is positioned based on the user's scroll position. An element with a sticky position is positioned like a relative element until it reaches a specified point, which becomes fixed. The top, right, bottom, and left properties to specify the distance from its containing block.