Positioning Elements with CSS

Shevaniett
featurepreneur
Published in
3 min readFeb 5, 2023

--

The position in CSS is used to specify the work of an element.

CSS has 5 different positions:

  1. static
  2. relative
  3. fixed
  4. absolute
  5. sticky

These positions work only if the position property is set first in CSS.

1. Static

By default, every element in CSS is positioned as static.

This has no special property, it is positioned according to the normal flow of the page.

Syntax:

.class/element/#id
{
position: static;
}

top, bottom, left, and right properties do not affect the elements which are positioned as static.

Example:

Code
Output

2. Relative

Relative position is used to position an element relative to its normal position.

top, right, bottom, and left properties of a relatively-positioned element will cause it to be adjusted away from its normal position.

Other content will not be adjusted to fit into any gap left by the element.

Syntax:

.class/element/#id
{
position: relative;
}

Example:

Code
Output

3. Fixed

The fixed position is used to position an element relative to the viewport.

This means that even when we scroll the page, the elements and contents stay in the same place.

top, right, bottom, and left properties are used to position the element.

Syntax:

.class/element/#id
{
position: fixed;
}

Example:

Code
Output

4. Absolute

absolute position is used to position an element relative to the nearest positioned elements.

If there are no such elements then the absolute use of the body of the page instead.

This is commonly used to remove the elements from the normal flow and overlap elements.

Syntax:

.class/element/#id
{
position: absolute;
}

Example:

Code
Output

5. Sticky

the sticky position is used to position an element based on the user’s scroll position.

Depending on the scroll position, a sticky element toggles between relative and fixed.

Syntax:

.class/element/#id
{
position: sticky;
}

the sticky position is not supported in Internet Explorer.

Example:

Code
Output before scrolling
Output after scrolling

--

--