A Brief Guide to Positions in CSS

A Brief Guide to Positions in CSS

What is Position In CSS

The CSS position property is used to specify how the element will be displayed on the page. The top, right, bottom, and left properties determine the final location of positioned elements.

Types of Positions in CSS

There is a total of 5 different types of Positions present in CSS.

    /* Positioning Types..*/
      position: static;
      position: relative;
      position: absolute;
      position: fixed;
      position: sticky;

Static

This is a default value, the element is positioned according to the normal flow of the document and static positioned elements are not affected by the top, bottom, left, and right properties.

#two {
position: static;
top: 5rem;
}

Here we set positioned to top: 5rem; but it doesn't affect static element.

Relative

The element is positioned relative to its normal position and the element's relative position will be determined by the position where the element was placed by the browser.

#three {
    position: relative;
    top: 5rem;
}

Relative: Before

Relative: After

Absolute

Here an absolutely positioned element is an element whose computed position value is absolute or fixed. When the parent is positioned relative and the element is positioned absolute, the top, bottom, left, and right will be with respect to the parent element.

#three{
  position: absolute;
  top:2rem;
  left: 6rem;
}

Absolute: Before

Absolute: After

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 to position the element.

#four {
  position: fixed;
  top: 5rem;
}

Sticky

This property is used when there is a chance to position sticky. This positioned element behaves normally as it has position: static but here we can define top, bottom, left, and right this property, and sticky is used when the given property is fulfilled to make its position.

#three {
position: sticky
left: 7rem;
}

Guidance from Hitesh Choudhary