Guide To CSS Position

Guide To CSS Position

The CSS position property defines the position of an element in a document. This property works with the left, right, top, bottom and z-index properties to determine the final position of an element on a page.

We have 5 Syntax in CSS position property:

position: static;
position: relative;
position: absolute;
position: fixed;
position: sticky;

Values used in position property:

top: 10px;
bottom: 20px;
left: 10px;
right: 20px;

/* This is just example values can be changed */

1. Position static:

.static {
      position: static;
      top: 25px;
      bottom: 25px;
    }

  • This is the default value for elements. The element is positioned according to the normal flow of the document. The left, right, top, bottom and z-index properties do not affect an element with position: static

  • position: static has no effect on the position of an element.

2. Position relative:

.relative {
      position: relative;
      top: 300px;
      left: 150px;
    }

  • Elements with position: relative remain in the normal flow of the document. But, unlike static elements, the left, right, top, bottom and z-index properties affect the position of the element.

3. Position absolute:

.absolute {
      position: absolute;
      top: 400px;
      left: 50px;
    }

  • Elements with position: absolute are positioned relative to their parent elements. In this case, the element is removed from the normal document flow. The other elements will behave as if that element is not in the document. No space is created for the element in the page layout. The values of left, top, bottom and right determine the final position of the element.

  • One thing to note is that an element with position: absolute is positioned relative to its closest positioned ancestor. That means that the parent element has to have a position of position: relative

  • If the closest parent element is not positioned, it is positioned relative to the next parent element that is positioned. If there's no positioned ancestor element, it is positioned relative to the <html> element.

  • In this example it is positioned relative to <html>

  • Scroll on the result tab to see the how position: absolute work.

4. Position fixed:

.fixed {
      position: fixed;
      top: 300px;
      left: 300px;
    }

  • Fixed position elements are similar to absolutely positioned elements. They are also removed from the normal flow of the document. But unlike absolutely positioned element, they are always positioned relative to the <html> element.

  • One thing to note is that fixed elements are not affected by scrolling. They always stay in the same position on the screen.

  • Scroll on the result tab to see the how position: fixed work.

5. Position sticky:

.sticky {
      position: sticky;
      top: 0px;
    }

  • Scroll on the result tab to see the how position: sticky work.