Search code examples
csscss-position

Understanding relative position in css


Following this link.

It states:

An element with position: relative; is positioned relative to its normal position.

How can we define 'normal position'? Is it in context of parent element or overall screen(viewport)?


Solution

  • "Normal position" is in the context of the DOM, and refers to Normal flow:

    First of all, individual element boxes are laid out by taking the elements' content, then adding any padding, border and margin around them.

    By default, a block level element's content is 100% of the width of its parent element, and as tall as its content. Inline elements are as tall as their content, and as wide as their content.

    This is explained in further detail in the CSS flow layout:

    Normal Flow, or Flow Layout, is the way that Block and Inline elements are displayed on a page before any changes are made to their layout. The flow is essentially a set of things that are all working together and know about each other in your layout. Once something is taken out of flow it works independently.

    In normal flow, inline elements display in the inline direction, that is in the direction words are displayed in a sentence according to the Writing Mode of the document. Block elements display one after the other, as paragraphs do in the Writing Mode of that document. In English therefore, inline elements display one after the other, starting on the left, and block elements start at the top and move down the page.


    It's worth noting that all elements have static positioning by default:

    Static positioning is the default that every element gets — it just means "put the element into its normal position in the document layout flow — nothing special to see here."

    And relative positioning simply allows for modification of the position:

    This is very similar to static positioning, except that once the positioned element has taken its place in the normal layout flow, you can then modify its final position. It is worth noting that position relative does accept all the box offset values - left, top, right and bottom. And once we use those values with position:relative; the element moves relative to itself from the offset. And the old position is also preserved, which means no other element in the flow will take that space by default. Also in case there is a nearby sibling element around position:relative element, and an offset is given to the element then the sibling element is not pushed (or moves away as is the case with margins and paddings), instead the position:relative element simply overlaps the sibling element in that case.