Position in CSS: Full detailed guide with example

Position in CSS: Full detailed guide with example

Positioning is one of the very important property in CSS. It is also one of the tricky and confusing property to understand in CSS.

Let's go and understand it in easy way.

First of all What is positioning?

This is the CSS property to set the position of Elements using the top, bottom, left, and right properties.

There are mainly 5 methods used in position:

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

1. position: static;

All HTML elements are positioned static by default. These elements are not affected by the top, bottom, left, and right properties.

Example

div.static {
  position: static;
  border: 3px solid black;
}

2. position: relative;

An element with a relative position will take a position relative to its normal position based on the value of top, bottom, left and right properties.

Example

.four {
  position: relative;
  right: 75px;
  top: 50px;
}

3. position: absolute;

The element is positioned relative to the nearest positioned ancestor. The original position does not affect this position. If it has no positioned ancestors, it uses the document body, and takes a position with the value of top, bottom, left and right properties.

Example

.three {
 position: absolute;
 right: 15px;
 top: 50px;
 z-index: 2;
}

4. position: fixed;

Using this property the element is set to the perticular place given by the value of any of 4 properties: top, bottom, left and right. No matter how much we scroll the page, the element stays fix to that position.

Example

div.fixed {
  position: fixed;
  bottom: 20;
  right: 20;
  padding: 20px;
  z-index: 2;
}

5. position: sticky;

Element with sticky position is positioned based on user's scroll position. It is used as combination of fixed and relative positioned. Element bahave like relative until the given offset position is met after that it stick to the place like fixed position. This is mainly use for building sticky navbar in website.

Example

.one {
  position: sticky;
  top: 0px;
  z-index: 1;
}