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;
}
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;
}
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;
}
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;
}
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; }