CSS Position - Detailed Overview

Introduction to CSS Position

The CSS position property specifies the type of positioning method used for an element. It determines how an element is positioned within its containing block and affects how it interacts with other elements.

Static Position

Static positioning is the default. Elements are positioned according to the normal flow of the document. Example:

.static-box {
    position: static;
    background-color: #d0e0f0;
    padding: 20px;
    border: 1px solid #ddd;
}

This box uses static positioning.

Relative Position

Relative positioning allows you to offset an element relative to its normal position. Example:

.relative-box {
    position: relative;
    background-color: #d0e0f0;
    padding: 20px;
    border: 1px solid #ddd;
}

This box is positioned relative to its normal position.
Absolute positioned box inside relative box

Absolute Position

Absolute positioning allows you to position an element relative to its nearest positioned ancestor. Example:

.absolute-box {
    position: absolute;
    top: 20px;
    right: 20px;
    background-color: #f0d0d0;
    padding: 20px;
    border: 1px solid #ddd;
}

This box is relatively positioned.
This box is positioned absolutely within the relative box.

Fixed Position

Fixed positioning allows you to fix an element relative to the viewport. Example:

.fixed-box {
    position: fixed;
    bottom: 20px;
    left: 20px;
    background-color: #d0f0d0;
    padding: 20px;
    border: 1px solid #ddd;
}

This box is fixed to the bottom-left of the viewport.

Sticky Position

Sticky positioning allows an element to switch between relative and fixed positioning depending on the scroll position. Example:

.sticky-box {
    position: sticky;
    top: 0;
    background-color: #d0e0f0;
    padding: 20px;
    border: 1px solid #ddd;
}

Scroll to see the sticky effect.