Let's learn position in CSS

Let's learn position in CSS

Position attribute is used to arrange elements in the web page. As the name suggests, it decides where to place an image. There are different five values, by which you can set the position of elements. Each value with its example is described below. Top, left, right and bottom attributes can be used with position to set an image.

Static:

Static is the default value of the position attribute. It set elements normally in the webpage.


position:static;

In the example, an element named one has a static position. There is no dimension given to it. By default, it is placed at the top-left corner of the page.

Fixed:

When a fixed position is applied to an element, it will not move from its original place by scrolling. Its use case is to make a chatbot. On many websites, this kind of feature is available. If Grammarly is on in hash node website, it is an example of a fixed position.

position:fixed;

In the example, the box given at the bottom right corner is an example of a fixed position. Even by scrolling the page, the Ask Me icon won't change its place.

Sticky:

A sticky position is used with a specific condition only. If there is a need to stick any element at a specific position in a webpage, at that time sticky can be applied. This element scrolls up to a specific position and then it will stick there and don't move.

position:sticky;

As shown in the example, in a header part sticky position is applied. The top is given to 2px. As the header will be 2px away from the top, it will stick there and the rest of the content will scroll only.

Relative:

Relative position set an element according to the previous position of the element.

position:relative;

As shown in the example, below the paragraph the box named two is given, whose position is relative. The top 20 px is applied to it. So, it shifted 20 px from its previous position, not from the top of the webpage.

Absolute:

The absolute position places an element according to its parent container.

position:absolute;

As shown in the example, the box named three is given. In this box, the top attribute is applied. So, from the top 1300px box is set. It does not consider its previous position.

Combined example: