Quick guide on CSS Positions

·

2 min read

Quick guide on CSS Positions

The position property states the type of positioning method used for an element. In other words, position property can be used to position an element.

There are five different Positions values:

  1. Static

  2. Relative

  3. Absolute

  4. Fixed

  5. Sticky

We can then position elements by using top, bottom, left, right properties. For the properties to work we need to set the position property. Now, lets get into the values.

  • position : static : This is the default position of HTML elements. Static position is not affected by any top, right, bottom, left property. Also, it is positioned as the normal flow of the page.

    div.static {
    position: static;
    border: 2px solid #FF0000;
    }
    
  • position : relative : The elements with position:relative is positioned in a normal way until and unless top, right, left, bottom property has been set. Setting these properties will cause the element to move form its normal position. Also, other elements position won't be affected.

    div.relative {
    position: relative;
    left: 30px;
    top : 10px;
    border: 2px solid #FFFF00;
    }
    
  • position : absolute : The element with position:absolute is removed from the document flow, and no space is created for the element in the page layout. It is positioned according to the nearest positioned parent element.

div.relative {
  position: relative;
  width: 300px;
  height: 200px;
  border: 4px solid #FFFFE0;
}

div.absolute {
  position: absolute;
  top: 80px;
  right: 0;
  width: 100px;
  height: 100px;
  border: 4px solid #FF0000;
}
  • position:fixed : The element with position:fixed is positioned relative to the viewport. It stays in the same and doesn't get affected by the scrolling. It can be positioned using top, bottom, right, left.

    div.fixed {
    position: fixed;
    bottom: 0;
    right: 0;
    width: 2px;
    border: 2px solid #FF0000;
    }
    
  • position:sticky : The element with position:sticky is positioned relative to the scroll's position. It is positioned relative until a given offset position then it "sticks" in place (like position:fixed).

    div.sticky {
    position: sticky;
    top: 0;
    background-color: #FF0000;
    border: 2px solid black;
    }