CSS Position

The position property specifies the type of positioning method used for an element (static, relative, fixed, absolute or sticky).

The position Property

There are five different position values:

  • static
  • relative
  • fixed
  • absolute
  • sticky

Elements are then positioned using the top, bottom, left, and right properties. However, these properties will not work unless the position property is set first. They also work differently depending on the position value.

Absolute Positioning

The element is removed from the normal document flow, and no space is created for the element in the page layout.

It is positioned relative to its closest positioned ancestor if any; otherwise, it is placed relative to the initial containing block. Its final position is determined by the values of toprightbottom, and left.

This value creates a new stacking context when the value of z-index is not auto. The margins of absolutely positioned boxes do not collapse with other margins.

See the Pen absolute css by Arpit (@soniarpit) on CodePen.

Relative Positioning

If we assign the value to position attribute to relative then the corresponding element gets placed at the relative position to the previous element.

An element with position: relative; is positioned relative to its normal position.

See the Pen relative css by Arpit (@soniarpit) on CodePen.

Static Positioning

By default all elements has static position.

Static positioned elements are not 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

See the Pen static css by Arpit (@soniarpit) on CodePen.

Fixed Positioning

The element is removed from the normal document flow, and no space is created for the element in the page layout.

It is positioned relative to the initial containing block established by the viewport, except when one of its ancestors has a transformperspective, or filter property set to something other than none (see the CSS Transforms Spec), in which case that ancestor behaves as the containing block. (Note that there are browser inconsistencies with perspective and filter contributing to containing block formation.) Its final position is determined by the values of toprightbottom, and left.

See the Pen ZEBJXeG by Arpit (@soniarpit) on CodePen.

Sticky Positioning

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).

See the Pen sticky by Arpit (@soniarpit) on CodePen.

Practice these examples because positioning is very useful in web designing.

Previous: CSS Lists

Next: CSS Animations