I am FIXED

Day 2 - Positioning

The position property specifies the type of positioning method used for an element.


1. Static Position (Default)

Elements display in order, as they appear in the document flow. top, left, etc. have no effect.

Code:

/* CSS */
.static-box {
    position: static;
}

Output:

Static
Next Box

2. Relative Position

Positioned relative to its normal position. Moving it does NOT affect the layout of other elements (it leaves a "ghost" space).

Code:

/* CSS */
.relative-box {
    position:  relative;
    top: 20px;  /* Move down 20px */
    left: 20px;  /* Move right 20px */
}

Output:

Before
Relative
After

3. Absolute Position

Positioned relative to the nearest positioned ancestor (like a parent with position: relative). It is removed from the normal document flow (no space reserved).

Code:

/* CSS */
.relative-container {
    position:  relative;  /* The Anchor */
    height:  250px;
}
            
.absolute-tl {
    position:  absolute;
    top: 0;
    left: 0;
}
            
.absolute-center {
    position:  absolute;
    top: 50%;
    left: 50%;
    transform:  translate(-50%, -50%); /* Centers it */
}

Output:

Top Left
Center
Bottom Right

4. Fixed Position

Positioned relative to the viewport (browser window). It stays in the same place even when scrolled.
Check the bottom-right corner of your screen!

Code:

/* CSS */
.fixed-box {
    position: fixed;
    bottom: 20px;
    right: 20px;
}

5. Sticky Position

Toggles between relative and fixed based on scroll position. It sticks when it reaches specific offset.

Code:

/* CSS */
.sticky-element {
    position: sticky;
    top: 0;  /* Sticks to top */
}

Output:

I am Sticky! (Scroll me)

Scroll down inside this box...

Keep scrolling...

The purple header sticks!


6. Z-Index (Stacking Order)

Controls which element sits on top of another. Higher number = on top.

Code:

/* CSS */
.z-1 {
    z-index: 1;
}  /* Bottom */
            
.z-2 {
    z-index: 2;
}
            
.z-3 {
    z-index: 3;
}  /* Top */

Output:

1
2
3