CSS made easy - The Position Property

CSS made easy - The Position Property

Position Property?

In CSS position property of an element signifies that where that element is going to be positioned in DOM(Document Object Model) based on it's value i.e. static, relative, absolute, fixed, sticky.

Values of CSS Positioning Properties

1. Static

Static is the default position that all of the HTML elements will have in the DOM when they are rendered in the page. Static position does not render the element in any special way, but just the way they should be. When the elements are positioned static, there's no effect of left, right, top and bottom property on the elements.

The below example does nothing but position the elements as static. If we do not set the position property as static, still the elements will be positioned as static by default.

2. Relative

When the position property of an HTML element is set to relative, It can be positioned relative to it's original place by setting top, right, left and bottom property.

For example, below I have set the first div position as relative and has set the top and left property to 20px each. You can see the div is shifted 20px from top as well as left from it's original place.

3. Absolute

In case of absolute the HTML element is removed from the DOM and than it is positioned relative to it's nearest ancestor whose position property is set to any value other than static. If there is no ancestor whose position is set relative or absolute or any other value other than static then that HTML element is positioned relative to body and will move when scroll.

For example, Below I have positioned parent div as relative and first div as absolute. You can see the first div is positioned relative to it's nearest ancestor i.e parent div.

4. Fixed

When the position property of an HTML element is set to fixed, it can be positioned relative to viewport. The element will be fixed at that position even when you scroll.

For example, Below I have set the first div as fixed. It will not move from it's position even when you move.

5. Sticky

Sticky Position is a combination of fixed and relative. When the element whose position is set to sticky it will positioned itself relative until a given threshold value of position is met in the viewport - then it gets fixed in that place.

In the below example I have set top equal to 10px, as soon as the div reaches threshold value of top: 10px while scrolling it gets fixed at that position.