Hack Frontend Community

CSS Position Property

The position property in CSS determines how an element will be placed on the page and what it will be positioned relative to.

Position Property Values

static

  • Default value.
  • Element is placed in the document according to the normal flow.
  • Does not respond to top, right, bottom, left, z-index properties.

Static example:

.element {
  position: static;
}

relative

Element remains in the flow but can be shifted using top, right, bottom, left. The space occupied by the element remains in place.

Relative example:

.element {
  position: relative;
  top: 10px; /* Shifts element down */
}

absolute

Element is removed from the flow and positioned relative to the nearest ancestor with position: relative, absolute, fixed, or sticky. If no such ancestor exists, it's positioned relative to body. Can use top, right, bottom, left properties.

Absolute example:

.container {
  position: relative;
}

.element {
  position: absolute;
  top: 0;
  left: 0; /* Positioned relative to container */
}

fixed

Element is removed from the flow and fixed relative to the browser window. Does not move when the page is scrolled. Used to create fixed elements such as headers or popup menus.

Fixed example:

.element {
  position: fixed;
  top: 0;
  left: 0;
}

sticky

Element behaves like relative while its parent block is in the visible area of the screen. Positioned relative to the browser window when scrolling, if it crosses the specified top, right, bottom, left values.

.element {
  position: sticky;
  top: 10px; /* Fixed as soon as it reaches 10px from the top of the screen */
}

Attention:

When using sticky, make sure the parent container has height. Otherwise, positioning won't work.

Comparison Table

PropertyDocument FlowPositioned Relative To
staticIn flowNot positioned
relativeIn flowItself
absoluteOut of flowNearest positioned ancestor or body
fixedOut of flowBrowser window
stickyIn flow until fixedNearest scrollable container or viewport boundaries