Positioning in CSS

Positioning in CSS

Everything we see on a web page is made up of blocks. And positioning those blocks in the proper spot is done by position property.

Position: static

By default, HTML elements are static. This means they are displayed on the page according to where they are in the natural HTML flow. Any changes to the elements will affect the position of other elements. It does not have Top, Left, Right, or Bottom properties.

div {
      position: static;
}

Position: relative

This positioning does not follow the document flow. Whatever value we set for Top, Left, Right, or Bottom, it positions the element relative to itself in other words we can say that it takes the reference of its initial position whenever its positions change.

div{
      position: relative;
}

Position: absolute

With an absolute position also element can placed at any place in a document. But, relative to the immediate parent. And yes, we can set values for all Top, Left, Right, or Bottom.

div{
      position: relative;
}

Position: fixed

It attaches an element fixed to the viewport and any scrolling of the page does not affect the element. It is used for any element that needs to be at a fixed position like Navbar.

div{
      position: fixed;
}

Position: sticky

Sticky positioning has traits of relative and fixed positioning. A sticky element is positioned relative to its initial position in the HTML flow until it crosses a specific threshold in the viewport.

div{
      position: sticky;
}