CSS Positions

·

2 min read

The Position property allows one to position elements based on five different position values.

  • static
  • relative
  • absolute
  • fixed
  • sticky

When position property is set to an element then CSS provides accessibility of top, right, bottom, right properties to align them.

Static HTML elements are positioned default as static according to the element flow, It cannot use top, right, bottom, right properties.

div{
  position: static; /*  There will be no change  */
}

Relative It helps in making the element move its position accordingly and also makes its child elements to hold within their flow when their child elements has position property of absolute.

div{
  position: relative; 
  left: 10px; /*  The div element gets the space of 10px on the left side */
}

Absolute It helps in the movement of elements according to their parent that contains relative positions, When there is no relative positions mentioned by default it takes body as their relative position.

div.one{
  position: relative;
}
div.two{
  position: absolute;
  right: 0;
  bottom: 0;  /* This moves the element to right bottom of the div elements with class one*/
}
<div class="one">
  <div class="two">
  </div>
</div>

Fixed It positions the element in relative to viewport, So no matter what it stays in the same position even when you scroll the page. Example : In some websites you can find scroll to top button when you reach the bottom.

div{
  position: fixed;
  right: 0;
  top: 0; /* It always stays in the right top position*/
}

Sticky It positions elements based on users scroll position. Example : In some websites the navigation bar will be after the cover image but on scrolling when it reaches the top it stays fixed there.

div{
  position: sticky;
  top: 0; /* It makes the div to be fixed when it reaches the top else it scrolls according to the page*/
}