CSS Positioning

CSS Positioning

positioning your element correctly will help page look better

Position

If we talk about physical meaning of position, we take it as place of existence / appearance .
when it comes to CSS , it almost same. The HTML elements are to be put in different parts of a web page to make it more readable or for aesthetic look. Syntax for CSS positioning

.selector{
   position: desiredPos;
}

Different Positions:

Static
Relative
Absolute
Fixed
Sticky

Using one of the five values above, an element can be positioned. We can then use the top, bottom, left and right properties to further define the element’s off-shift position on the page. We’ll discuss how this works in this article.

Static

This is the default value that browser takes if you do not provide any value to HTML element.
You can find all CSS properties of elements in browser>inspect>computed Screenshot 2022-07-18 at 8.36.04 PM.png

Relative

The HTML element would shift relative to it's original/initial position. We determine the amount of offset, set values for the top, right, bottom, and left properties. The other elements aren’t affected, but there will be nothing in space where the element would have been.

.relativeDiv {
width: 100px;
height: 100px;
position: relative;
top: 20px;
left: 50px;
}

Absolute

At {position: absolute;} the element ignores the normal document flow & is positioned with respect to its nearest positioned ancestor.

Basically, the element is position relative to its nearest positioned ancestor.

And if none of its ancestors is positioned, then the element is positioned according to the viewport moves with scrolling.

Fixed

At {position: fixed;} the element is positioned relative to the viewport. As the name suggests, the HTML is fixed at the defined position, even if the page is scrolled.

.fixedDiv {
width: 100px;
height: 100px;
position: fixed;
top: 20px;
right: 50px;
}

Sticky

The {position: sticky;} is a combination of position relative and position fixed. The element's position is determined by the user's scroll. The element will behave like a relative positioned element until the viewport meets a specified position. And then the element would get "fixed" in that spot. In this position element always appears on screen if we scroll page beyond view port also.

.stickyDiv {
position: sticky;
top: 10px;
}