CSS (a guide to position property)

CSS (a guide to position property)

Hey there , today we are going to learn about the "Position property" in css. It is one of the most widely used properties of css and so it requires a deep dive to understand it's usage completely.

But first of all let's figure out...

What is this "Position property"?

The CSS position property defines the position of an element in a document. This property works with the left, right, top, bottom and z-index properties to determine the final position of an element on a page.

There are five values the position property can take. They are:

  • static
  • relative
  • absolute
  • fixed
  • sticky

Let's have a look on each of them:

  • Static

    All the elements are positioned static in CSS by default. If static is used as the positioning method, elements do not get affected by top, bottom, left, right and z-index. Basically, elements with this type of positioning are set according to the normal flow of the program.
  div.static 
  {
    position: static;
    border: 2px solid #FF0000;
  }
  • Relative

    This is the positioning method which is set according to the normal flow of the program by default, but, it can be affected by properties like top, bottom, left, right and z-index. The use of the said properties will not affect the positioning of other elements and wont make other elements adjust to any gap left by the element that used relative positioning method.
div.relative 
{
  position: relative;
  left: 30px;
  top : 10px;
  border: 2px solid #FFFF00;
}
  • Fixed

    The elements using this method are set according to the viewport using the top, bottom, left and right properties. These elements always stay fixed to their position even if you scroll. When using this method, the element is first removed from the webpage and then used in a different position set by the user and due to this no space is left behind in the normal flow.
div.fixed
{
  position: fixed;
  bottom: 0;
  right: 0;
  width: 2px;
  border: 2px solid #FF0000;
 }
  • Absolute

    Elements using this positioning method are set relatively according to the closest parent element. The element is removed from the webpage and no new space is created for it. This is why elements using this method overlap with other elements.
div.absolute 
{
  position: absolute;
  top: 80px;
  right: 0;
  width: 100px;
  height: 100px;
  border: 4px solid #FF0000;
}
  • Sticky

    These elements are positioned relatively to the user's scroll bar position. This method is kind of in the middle of relative and fixed method. When the user has not used the scroll bar to move through the entire viewport the method uses relative. But when that offset is met it switches to fixed.
div.sticky
{
position: sticky;
top: 0;
background-color: #FF0000;
border: 2px solid black;
}