Css Positioning

Css Positioning

The CSS Position property is used to specify where an element is displayed on the page. When paired with the 'top', 'right', 'left' and 'bottom' CSS properties, the position property determines the final Position of an Element on the page. This property takes 5 values:-

  • Static

  • Relative

  • Absolute

  • Sticky

  • Fixed

Static Position:-

By default, the position for all HTML elements in CSS is set to Static. This means that if the position property is not declared, It will be Static.

Here, three boxes are created in HTML without applying any special positioning to "box3", it will remain in its default static position, so any changes made to its position will have no visible effect.

Relative Position:-

The box position is calculated according to the normal flow by applying the 'top', 'right', 'left' and 'bottom' properties. The relatively positioned element will cause it to be adjusted away from its normal position. Other content will not be adjusted to fit into any gap left by the element.

Here the property of box2 is changed it is set to relative, from 'top:30px'. So the changes are visible.

Absolute Position:-

'Position: absolute' lets you move an element anywhere on the page by adjusting its 'top', 'left', 'right', and 'bottom' properties. It's taken out of the normal flow, and if it lacks a parent with a defined position, it defaults to the document body for reference.

Box 2 shifts from its original position. With "position: absolute," it's moved 80px down from the top and 10px in from the right.

Sticky Position:-

In this case, elements stay in place as the user scrolls, allowing them to switch between fixed and relative positioning based on the scroll position. This is commonly used for elements like navigation bars to keep them visible as the user scrolls.

Here, we've applied the "sticky" property to box 2, making it stick to the top, specifically at 1px, even when we scroll.

Fixed Position:-

An element with position: fixed; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled. The top, right, bottom, and left properties are used to position the element.

Here, we've applied the "fixed" property to box 2, making it stick to the top at 110px and the left at 250px, even when we scroll.

Here are the CSS positions, as mentioned at the beginning of the article.