DEV Community

Abdullah Al Numan
Abdullah Al Numan

Posted on

What's the difference between a relative, fixed, absolute and statically positioned element?

In CSS, elements can be categorized according to how they can be positioned in the document flow. There are two primary types: non-positioned and positioned elements. Positioned elements can further be divided into relatively positioned, absolutely positioned and stickily positioned elements.

Their differences lie in how they behave in relation to the normal flow of the document, how they react to position parameter values, and whether they are assigned a space in the page layout or not.

Non-positioned / Static Elements
A non-positioned element is an element whose position cannot be changed by setting a top, bottom, right and left property. It is, in effect, a Statically Positioned element which has its position property set to static. All elements are set to have a static position by default. The element is positioned according to the normal flow of the document.

Relatively Positioned Elements
Relatively positioned elements have their position set to relative. They also remain in the document flow, but can change their positions with offset values set by top, bottom, right and left. It is important to note that relatively positioned elements change their position relative to themselves, i.e. relative to their otherwise static position.

Absolutely Positioned Elements
Absolutely positioned elements can have their position set to either absolute or fixed -- each coming with slightly distinct behaviors. They are removed from the flow of the document and not assigned any space. By default, they occupy the top-left corner of their containing block. Their position can be changed with top, bottom, right and left values.

There is a difference between elements with position: absolute; and those with position: fixed; depending on where their containing blocks are located in the DOM tree. For position: absolute, the element's containing block is its nearest positioned (or non-static) ancestor - and so its position parameter values are applied relative to that container's edges. In contrast, for position: fixed, its containing block is the initial containing block (<html> element) or any ancestor which has a value other than none for any of transform, perspective, or filter properties. And so they are positioned relative to the viewport or any qualified containing block.


References

  1. Position
  2. Layout and the containing block

Top comments (0)