Set the correct position with the Position property of CSS

Set the correct position with the Position property of CSS

Introduction

The position property of CSS helps to set the position of an HTML element or entity in a document. We often face trouble in locating an entity in the exact position we need and tend to use top, left, right, bottom, and many other properties, but fail to do so. The position property with its different values makes it very easy to perfectly position an element in the exact location.


Types of values of the Position property

static

Static is the default positioning method. HTML elements are positioned according to the normal flow of the document. Properties like top, bottom, left, right, z-index will have no effect on static positioned elements.

relative

In relative positioning, initially, the HTML elements are positioned according to the normal flow of the document then they are positioned relative to their normal position with the help of properties like top, left, right, bottom and will leave a gap in its normal position. It does not affect the position of any other element. This is mostly used to stick navbar at the top.

absolute

By stating position: absolute, the element is removed from the normal document flow without creating any space for it in the page layout and will be positioned in the exact location based on the values of top, left, right, bottom properties. The position of the element is relative to the position of its first parent.

fixed

By using position: fixed, an element is fixed at a particular position on the page and stays in the same place even if the page is scrolled. This happens because the elements are positioned relative to the browser window. The element is removed from the normal document flow without creating any space for it in the page layout and will be positioned in the exact location based on the values specified by top, left, right, bottom properties. This is widely used for positioning chat box on a fixed area of the page.

sticky

The position of a sticky positioned element depends on the user's scroll position. It is a combination of both relative and fixed positions and toggles between the two depending on the scroll position. Initially, it is positioned relative and then becomes fixed at a place until a given offset position is met in the viewport.


That's it. If you want to know more, refer CSS Positions - MDN.

Happy coding !!