Positioning In CSS

Positioning In CSS

The position Property

In CSS the position property defines the type of the position method for any HTML Element.

the position property allows you to place HTML elements in any place inside the page by setting the offsets of the element, like left, right, top and bottom. Each position value has it's own behavior.

position types

static

the position static is the default value for every html element.

the elements who's position is static it will not be affected by the top, bottom, left, and right properties.

An element with position: static; is not positioned in any special way; it is always positioned according to the normal flow of the page

P{
position: static;
}

Example:

relative

the element who's position is static, is positioned relatively to its normal position. That means when you set the top, left, right and bottom values it will cause it to adjust away from its normal position.

p{
position: relative;
}

Example:

Fixed

the element who's position is static, 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 to position the element.

p{
position: fixed;
}

Example:

absolute

the element who's position is absolute, is positioned relative to the nearest ancestor who's position is relative, which means setting The top, right, bottom, and left properties will adjust it to move away from this ancestor, But incase if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.

div{
position: absolute;
}

Example When there is a positioned ancestor : in this example we will notice that the absolute element will be adjusted away from the nearest ancestor who's positioned value is relative.

Example When there is no positioned ancestor : in this example we will notice that the absolute element will be adjusted away from the document body.

sticky

An element with position: sticky; is positioned based on the user's scroll position.

A sticky element toggles between relative and fixed, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it "sticks" in place (like position:fixed).

Example: