A Complete Guide on CSS Positions

A Complete Guide on CSS Positions

In order to control the positioning properties of the elements the CSS selectors are used. For example, the user wants the elements or buttons to be top of the one another or next to each other. In order to achieve these, we use the CSS selectors so that we can position the elements exactly the place we want them to be.

The CSS selectors are divided into five values. >

  • Static
  • absolute
  • relative
  • sticky
  • Fixed

position:static : The static is the default position set to all the HTML elements in CSS. In other words, if we do not specify any CSS selector it automatically takes it static. Static position is not affected by any right, left, bottom, top direction.

.class{
position: static;
border: 2px solid #FF0000;
}
`

position: relative: The relative position behaves same as the static but it lets us change the position of the element. In this we need to give the values to top, bottom, left and right. These top, bottom, left, right position values push the elements away from their original position in the reverse direction. The top pushes the element towards the bottom, left pushes the element to the right and vice-versa.

.class {
position: relative;
left: 50px;
top : 20px;
border: 4px solid #FFFF00;
}

position: absolute: the element with the position :absolute does not depend on its sibling or element at the same level and will be positioned with respect to its nearest non-static ancestor.

.class{
  position: relative;
  width: 300px;
  height: 200px;
  border: 4px solid #FFFFE0;
}
.class{
  position: absolute;
  top: 80px;
  right: 0;
  width: 100px;
  height: 100px;
  border: 4px solid #FF0000;

}
`

position:fixed: the element with position:fixed remains at the same place even scrolling. This is set according to the viewport. The application or use-case of position:fixed can be used in navigation-bar where you want to stay at the same position no matter how much scrolling is done.

.class{

position: fixed;
bottom: 0;
right: 0;
width: 4px;
border: 3px solid #FF0000;
}

position:sticky: the element with position:sticky behaves same as the static but as user past-scroll it, if its parent element has room, the sticky element will behave as if it’s fixed until that parent element is out of room.

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