Positioning in CSS refers to the Position property, which specifies the position of an element on the page.

The position property has five values:

  • static
  • relative
  • position
  • fixed
  • sticky

Let’s take a look at it one by one.

The static positioning

The default value for the element position attribute. The elements are arranged in the normal flow of the page. The element is not affected by the left, top, right, and bottom values.

Relative positioning

Relative means relative position, relative to the normal position of an element. It doesn’t change the amount of space it takes up when it’s offset.

.box {
  position: relative;
  top: 100px;
  left: 100px;
}
Copy the code

Elements with relative positioning are generally used as containers for absolute positioning.

Absolute positioning

Absolute: An absolutely positioned element is positioned relative to its nearest positioned parent (not static). If an element has no positioned parent, its position is relative to the browser window.

Fixed position

Fixed is fixed. In contrast to a browser window, fixed elements are always fixed, that is, they do not scroll with the page.

.box {
  position: fixed;
  top: 10px;
  left: 10px;
}
Copy the code

Sticky positioning

Sticky positioning is not quite the same as the previous ones, and it automatically produces a “top sucking effect”. The navigation bar on some websites, for example, will initially be in its default position. When the page scrolls down, the navigation bar will be fixed at the top of the page, close to the upper edge of the browser viewport. When the page scrolls up, it automatically returns to its original position. This effect can be achieved by using sticky.

.box {
  margin-top: 100px;
  position: sticky;
  top: 0;
  left: 10px;
}
Copy the code

Before sticky, we used to achieve this effect through fixed positioning with Scroll events.