CSS Positioning

The CSS position property has four values that can be used to position elements on the page:

  • Static
  • Fixed
  • Absolute
  • Relative

Static is the default. I will use two boxes in a container with some paragraphs around between each box to demonstrate:

These are block elements with no position property assigned. Therefore, they’re positioned statically, and flow as usual in the document. What if I make the boxes fixed?

The boxes are stacked on top of one another. The reason there is some space between box 1 and 2 is the middle paragraph element; remove it, and the second box sits completely atop the first. The fixed elements are rendered where they would normally begin in the flow of the document as if they were static, but the content that follows continues to render:

If the position is absolute, not much appears to have changed from the position being set to fixed:

The difference between absolute and fixed positioning is that fixed elements will remain in the same spot even as the page scrolls (an often-used example is a navigation bar that “sticks” to the top of the page as your scroll). Both positions remove the element from the flow of the page and position it relative to the viewport (in this case, the browser window) on a coordinate plane. I can therefore set where on the page the boxes should go:

Finally, relative positioning renders the element as it would be if it were static, then adjusts the position of the element relative to itself. The below elements have a relative position. Without any top/right/bottom/left property on the selector, the boxes behave just like a statically-positioned element. However, if I add the left property and set its value to -10px, the elements shift 10 pixels to the left:

The space for the element remains between the paragraphs even though I can shift the elements quite far away from it:

These are the four currently-supported positioning properties for a CSS selector.