CSS Positioning

CSS positioning is about controlling the placement of elements within a web page.

With CSS positioning, you can override the normal document flow.


The CSS position Property

The position property specifies the positioning type for an element.

This property can have one of the following values:

Elements are then positioned to their final location with the topbottomleft, and right properties.

CSS position: static

All HTML elements are positioned static by default.

Static positioned elements are not affected by the top, bottom, left, and right properties.

An element with position: static; is always positioned according to the normal flow of the page:

CSS position: relative

An element with position: relative; is positioned relative to its normal position in the document flow.

Setting the top, right, bottom, and left properties will cause the element to be adjusted away from its normal position. Other content will not be adjusted to fit into any gap left by the element.

CSS position: fixed

An element with position: fixed; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled. The top, right, bottom, and left properties are used set the final location of the element.

A fixed element does not leave a gap in the page where it would normally have been located.

This <div> element has position: fixed;

Notice the fixed element in the lower-right corner of the page. Here is the CSS that is used:

CSS position: absolute

An element with position: absolute; is positioned relative to the nearest positioned ancestor (with position other than static).

However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.

Note: Absolute positioned elements are removed from the normal document flow, and can overlap other elements.

Here is a simple example:

Positioning Text On an Image

How to position text on an image:

CSS position: sticky

An element with position: sticky; toggles between a relative and fixed position, depending on the scroll position.

A sticky element is positioned relative until a certain scroll position is reached – then it “sticks” in that place (like position:fixed).

All CSS Positioning Properties