DEV Community

Albert Chang
Albert Chang

Posted on • Edited on

CSS Position Property

What does this property do?

It determines how an element is positioned in the document.

Some Clarifications

  • offset properties refers to top/right/bottom/left properties
  • an element's natural position / where an element would naturally be refers to the element without position property defined on it
  • positioned element refers to an element with display set to anything other than static

All CSS Position Values

  • position:static; (default)
  • position:relative;
  • position:absolute;
  • position:fixed;
  • position:sticky;

static

  1. The default value.
  2. Cannot use offset properties.

relative

  1. Allows use of offset properties.
  2. The offset properties are based on where the element would naturally be.
  3. The elements around it will treat this element as if it still sits in its natural position regardless if offset properties are used.

absolute

  1. Allows use of offset properties.
  2. The offset properties are based on the closest non-static ancestor or the initial viewport. This means that if the body is scrollable the absolute element will not move with the viewport.
  3. Elements around it will treat it as if it doesn't exit.

fixed

  1. Allows use of offset properties.
  2. The offset properties are based on the viewport(not the initial viewport) or if any ancestor has transform, perspective or filter set to anything other than none.
  3. Elements around it will treat it as if it doesn't exit.

sticky

  1. Allows use of offset properties.
  2. The offset properties are based on nearest ancestor with overflow set to anything other than visible. If it cannot find one, it uses <html> or <body>, check using document.scrollingElement. Another way to think of offset values is it is the minimum gap between the element and the edge of the viewport while the container is in-frame.
  3. The element is also constrained by its closest block level ancestor. i.e. it cannot leave that ancestor.
  4. The elements around it will treat this element as if it still sits in its natural position regardless if offset properties are used.

Summary

  1. Positioned elements all allow the use of offset properties.
  2. Elements around static, relative, sticky elements will treat them as if they are still in their natural positions.
  3. Elements around absolute and fixed elements will treat them as if they don't exist.

Top comments (4)

Collapse
 
atulcodex profile image
🚩 Atul Prajapati 🇮🇳

Wow, I have struggled a lot to understand this CSS positions thanks for your efforts to explaining all this :)

Collapse
 
a89529294 profile image
Albert Chang

You're welcome!

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
a89529294 profile image
Albert Chang

Thanks for the encouragement!