What is positioning in CSS?

CSS lets you style elements on your page, including where they are and how they look. CSS has a special rule called the position property. This property is applied to a specific element on the page, and determines where on the page that element is displayed.

There are five position values that can be applied to an element:

  • static
  • relative
  • fixed
  • absolute
  • sticky

In this blog post, we'll look at the relative, absolute, and fixed positioning properties.


What's the difference between relative, absolute, and fixed positioning?

Relative

With relative positioning, the element is positioned relative to its normal position. In other words, the element sits in its normal position by default, and you can move it around from there. You do this using the properties of top, right, bottom, and left.

For example, top: 45px adds 45px to the element's 'top' position, which would push it down the page by 45 pixels.

Absolute

If the absolute property is applied, the element is positioned relative to the first one of the previous elements to have a positioning property applied (other than static, which is the default).

If the element has no previous elements with a positioning property applied, the element is positioned relative to the document body instead. As a result, in this situation the element will move as the page is scrolled.

Absolute elements can overlap other elements.

For example, an absolute element with the properties of top: 0px and right: 0px would sit on the top right of the page, overlapping any previous positioned elements or the body of the page itself.

Blue absolute div overlapping a red relative div

Fixed

With fixed positioning, the element's positioning is relative to the user's browser window. This means that no matter how much the user scrolls up or down, the fixed element will always appear in the same spot.

For example, a fixed element with the properties of top: 10px and left: 10px would sit 10px away from the top left of the screen, no matter how far the user scrolls down the page.

Blue fixed div overlapping a red body element