CSS Positioning
The position Property
CSS
.box { position: static; /* DEFAULT — normal flow, top/left/etc. ignored */ position: relative; /* offset from its normal position */ position: absolute; /* removed from flow, positioned to nearest relative parent */ position: fixed; /* stays fixed on screen when scrolling */ position: sticky; /* normal flow until scrolled to threshold, then fixed */ }
relative — Offset from Itself
CSS
.box { position: relative; top: 20px; /* move DOWN 20px from normal position */ left: 10px; /* move RIGHT 10px from normal position */ } /* Original space is still reserved */ /* Also used as anchor for absolute children */
absolute — Position Relative to Parent
CSS
/* Parent must have position: relative (or any non-static) */ .card { position: relative; } .badge { position: absolute; top: 10px; right: 10px; /* placed 10px from top-right corner of .card */ } /* Center absolutely positioned element */ .centered { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
fixed — Sticks to the Screen
CSS
/* Sticky navbar */ header { position: fixed; top: 0; left: 0; right: 0; z-index: 100; } /* Add padding-top to body so content isn't hidden under header */ body { padding-top: 64px; } /* Back-to-top button */ .back-top { position: fixed; bottom: 2rem; right: 2rem; }
sticky — Best of Both
CSS
/* Scrolls normally, then sticks at threshold */ nav { position: sticky; top: 0; /* sticks when it reaches the top */ z-index: 10; } /* Table headers that stick while scrolling */ th { position: sticky; top: 0; background: white; }
z-index — Stacking Order
CSS
/* Higher z-index = on top. Only works on positioned elements. */ .modal { position: fixed; z-index: 1000; } .overlay { position: fixed; z-index: 999; } .navbar { position: sticky; z-index: 100; } .card { position: relative; z-index: 1; }