CSS Positioning

Explore detailed examples of CSS positioning with enhanced visuals.

1. Static Positioning

Static is the default positioning for elements. It places the element according to the normal document flow.

.box {
    position: static;
}
                
Static

2. Relative Positioning

Relative positioning offsets the element from its normal position in the document flow.

.box {
    position: relative;
    top: 20px;
    left: 20px;
}
                
Relative

3. Absolute Positioning

Absolute positioning places the element relative to its nearest positioned ancestor.

.container {
    position: relative;
}
.box {
    position: absolute;
    top: 10px;
    left: 10px;
}
                
Absolute

4. Fixed Positioning

Fixed positioning pins the element to the viewport, regardless of scrolling.

.box {
    position: fixed;
    bottom: 10px;
    right: 10px;
}
                
Fixed

5. Sticky Positioning

Sticky positioning toggles between relative and fixed positioning based on the scroll position.

.box {
    position: sticky;
    top: 0;
}
                
Sticky

Scroll to see the sticky effect in action.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin ut velit nisl.

6. Z-Index

Z-index specifies the stack order of elements. Higher values appear in front of lower values.

.z-box-1 { z-index: 1; }
.z-box-2 { z-index: 2; }
.z-box-3 { z-index: 3; }
                
Z=1
Z=2
Z=3

7. Initial

The default positioning value, which is equivalent to `static` unless explicitly set.

.box {
    position: initial;
}
            
Initial

8. Inherit

Inherits the positioning value from the parent element.

.parent {
    position: relative;
}
.child {
    position: inherit;
}
            
Parent (relative)
Inherit

9. Combining Z-Index and Position

Z-index only works on positioned elements (relative, absolute, fixed).

.box {
    position: absolute;
    z-index: 2;
}
.background {
    position: absolute;
    z-index: 1;
}
            
Background
Foreground

10. Positioning Contexts

Positioned elements are placed relative to the nearest ancestor with a position other than `static`.

.ancestor {
    position: relative;
}
.child {
    position: absolute;
    top: 10px;
    left: 10px;
}
            
Ancestor (relative)
Child (absolute)

11. Overflow with Position

Positioned elements can overflow their containers based on CSS overflow properties.

.container {
    position: relative;
    overflow: hidden;
}
.box {
    position: absolute;
    top: 20px;
    left: 20px;
}
            
Container (overflow: hidden)
Overflow Box

12. Positioned Images

Position images creatively using relative, absolute, and fixed positioning.

.image {
    position: absolute;
    top: 20px;
    left: 20px;
}
            
Image

Additional Resources