HTML-CSS-Position

Quick guide about css-position

HTML-CSS-Position

Table of contents

CSS Position

The CSS position property is used to set position for an element. it is also used to place an element behind another and also useful for scripted animation effect. The top,right,bottom, andleftproperties determine the final location of positioned elements.

Let's have a look at following CSS positioning:

  1. static
  2. relative
  3. fixed
  4. absolute
  5. sticky
  1. static

The element is positioned according to the normal flow of the document. The top,right, bottom, left, and z-index properties have no effect. This is the default value.

div.static {
  position: static;
  border: 3px solid #73AD21;
}

2.relative

An element with position: relative; is positioned relative to its normal position. Setting the top, right, bottom, andleft properties of a relatively-positioned element will cause it to be adjusted away from its normal position. Other content will not be adjusted to fit into any gap left by the element.

div.relative {
  position: relative;
  left: 30px;
  border: 3px solid #73AD21;
}

3.fixed

An element with position: fixed; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled. The top,right,bottom, and leftproperties are used to position the element. Here is the CSS that is used:

div.fixed {
  position: fixed;
  bottom: 0;
  right: 0;
  width: 300px;
  border: 3px solid #73AD21;
}

4.absolute

The position: absolute; is used to position an element relative to the first parent element that has a position other than static. If no such element is found, the containing block is HTML.

//this is parent element
div.relative {
  position: relative;
  width: 400px;
  height: 200px;
  border: 3px solid #73AD21;
}
//this is child element 
div.absolute {
  position: absolute;
  top: 80px;
  right: 0;
  width: 200px;
  height: 100px;
  border: 3px solid #73AD21;
}

5.sticky

The position: sticky; is positioned according to the normal flow of the document, and then offset relative to its nearest scrolling ancestor and containing block (nearest block-level ancestor), including table-related elements, based on the values of top,right, bottom, and left. The offset does not affect the position of any other elements.

div.sticky {
  position: sticky;
  top: 0;
  background-color: green;
  border: 2px solid #4CAF50;
}