Understanding CSS positioning with examples.

Understanding CSS positioning with examples.

What is CSS position?

  • The CSS position 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.
  • There are five types of position in css:
    • Static
    • Relative
    • Absolute
    • Sticky
    • Fixed

Static positioning:

  • This is the default value for all elements. This is how all elements are laid out on the webpage.
  • Using position: static will not affect the position of that element.

    Example

Static.png

Relative positioning:

  • By using position relative the element remains in its original document flow unlike position absolute we can use top, bottom, left, and right to change the position of an element from its original position.

Example

relative op.png

Absolute positioning:

  • Absolute Positioning elements are positioned differently than the relatively positioned elements.
    • They are positioned according to the nearest containing element with position.
    • If it didn't find any parent element containing position then it will be positioned according to the body.
    • when we use position absolute the element gets removed from the original document flow, As a result, the other elements will behave as if it never existed.

Example

Screenshot (91).png

Sticky positioning:

  • Sticky are positioned depending on the user's scroll.
  • Depending on how far user has scrolled down page, a sticky element behaves like a relative element until it meets a specified position.
  • Then it becomes fixed in a spot and appears to stick to page as the user scrolls.

Example

Before scrolling

Screenshot (94).png

After scrolling

Screenshot (95).png

Fixed positioning:

  • Fixed elements do not move when the user scrolls & unlike relative they do not leave blank space where the element would been positioned.
  • You can use the top, right, bottom & left properties to set the fixed element's final position.

Example

Screenshot (96).png