CSS Positioning

CSS positioning allows you to control exactly where an element appears on the page. With positioning, you can move elements freely, overlap them, or make them stay fixed on the screen even when scrolling.


Position: static

This is the default position for all elements. Elements appear in normal page flow, and top, left, right, bottom do not work.

Syntax:

position: static;

Example:

.box {
  position: static;
  background: lightblue;
}

Static element


Position: relative

A relatively positioned element behaves like static, but you can shift it using top, left, right, bottom. The space it originally occupies is still preserved.

Syntax:

position: relative;
top: 20px;
left: 30px;

Example:

.box {
  position: relative;
  top: 20px;
  left: 30px;
  background: coral;
}

Relative element (moved 20px down & 30px right)


Position: absolute

An absolutely positioned element is removed from normal page flow and positioned relative to the nearest positioned ancestor (if none, it uses <body>).

Syntax:

position: absolute;
top: 10px;
right: 20px;

Example:

.parent { position: relative; }
.child {
  position: absolute;
  top: 10px;
  right: 20px;
  background: lightgreen;
}

Absolute element
Parent element (relative)


Position: fixed

A fixed element stays in the same place on the screen even when the page is scrolled. Commonly used for navigation bars or floating buttons.

Syntax:

position: fixed;
bottom: 20px;
right: 20px;

Example:

.button {
  position: fixed;
  bottom: 20px;
  right: 20px;
  background: gold;
}



Position: sticky

A sticky element switches between relative and fixed depending on scroll. It sticks to a position when reached.

Syntax:

position: sticky;
top: 0;

Example:

.header {
  position: sticky;
  top: 0;
  background: pink;
}

Sticky Header

Scroll down...

Lorem ipsum dolor sit amet...

Lorem ipsum dolor sit amet...



Z-Index

Controls which element appears on top when elements overlap. Higher value = brought to front.

Syntax:

z-index: 5;

Example:

.box1 { position: absolute; z-index: 1; }
.box2 { position: absolute; z-index: 5; }

Z-index 1
Z-index 5 (on top)
HTML Logo