Beginner's guide to the CSS Position property.

Beginner's guide to the CSS Position property.

The CSS position property is used to set position for html elements. Positioning is what makes us determine where elements appear on the screen, and how they appear. By default, all elements in html are positioned statically. We can move elements around, and position them exactly where you want. You can position an element using the top, right, bottom, left, and z-index properties.

Type of CSS Positions

1. Static

2. Relative

3. Fixed

4. Absolute

1. Static:-

Static positioning is the default value for an element. Static positioned elements are displayed in the normal page flow. Static positioned elements are not affected by the top, bottom, left, and right properties. it is always positioned according to the normal flow of the page.

Example-

      div.static {
      position: static;
      border: 2px solid black;
       }

Output-

Screenshot 2022-07-22 231624.png

2. Relative-

Relative position means actual position of an html element with respect to its original position. Relative position allows us to use more css properties. We can use left, right, top, bottom, z-index with the relative positioning.

Example-

     div.relative {
     position: relative;
     top:20px;
     left: 20px;
     border: 2px solid black ;
     }

Output-

Screenshot 2022-07-22 232737.png

3. Fixed-

An element which is fixed positioned, will be positioned relative to the viewport. The element which uses fixed positioning ,will be fixed at same position, even after page scrolling. With fixed positioning we can use left, right, top, bottom properties.

Example-

     .div {
       position: fixed;  
       top: 0px;
       left: 0px;
       border: 2px solid black ;
       }

Output-

Screenshot 2022-07-22 234530.png

4. Absolute-

An element with position absolute does not take position relative to the viewport(fixed position),but it takes position relative to it's ancestors(parent). Remember in relative positioning that we noticed the space originally occupied by an element was preserved even if it was moved around? With absolute positioning, as soon as we set position: absolute on .div, its original space is now collapsed, and only the origin remain the same.

Example-

     .div{
       position: absolute;
       top:40px;
       left:0px;
       border: 2px solid black ;
       }

Output-

Screenshot 2022-07-22 235754.png