Positions in CSS

Positions in CSS

What is Position?

Position is a property in CSS that you can apply to any element in the document. It lets you change the position of that element. After applying the position property, the properties top, right, bottom and left are applied to determine the changes in the position of the element. For example,

div {
    position: relative;
    top: 50px;
    left: 50px;
}

The Position property has the values - static, relative, absolute, fixed and sticky. Let's see all of them one by one.

Static

Static is the default position of all the elements. The elements are static if they are structured according to the HTML document's normal flow. So, there's no need for the properties top, right, bottom and left .

Relative

The relative value changes the position of the element relative to where it is positioned. The HTML document's normal flow will remain the same but the targeted element will change it's location according to the values given for top, right, bottom and left . For example,

In the above example, all three boxes were in line before applying position:relative; property to the box-2 element. It changed it's location according to the values of top and left .

Absolute

With this property value, the targeted element is basically removed from the flow of the document and it's place is taken by other elements in the web page. The element is positioned relative to it's parent element. For example,

In this example, the position: absolute; is applied to the green box. As you can see that the green box's previous place is taken by the blue box and the green box's location is determined relative to it's parent element i.e body tag.

Fixed

Like absolute, this value also removes the element from the flow of document. The difference between the two is, in absolute, the element changes it's position relative to its parent element. While in fixed, the element will always be relative directly to the document and not any other element. For example,

If you scroll down in the above example, you can see that the red box remains in it's position. That's because it's relative to the document and not it's parent element section .

Sticky

This is a little bit similar to fixed with one difference. The element is not removed form the document flow and behaves like a normal element until when you scroll down the web page and it touches the top roof of web page. As soon as it reaches the top, it starts to behave like fixed value. Let's see an example,

Scroll down in the above example to see how the blue box behaves as a sticky element.