</>HTML & CSS
IntermediateLesson 8 of 15

Positioning & Stacking Order – HTML & CSS

relative, absolute, fixed, sticky and z-index.

With position you take elements out of normal flow. static is the default. relative shifts visually (with top/left/…) but still occupies its original space and serves as a reference point. absolute removes the element from the flow and positions it relative to the nearest positioned ancestor (position ≠ static). fixed refers to the browser window, sticky sticks when scrolling.

<!DOCTYPE html>
<style>body{font:16px system-ui,sans-serif;margin:12px;background:#fff;color:#222}
.produkt { position: relative; width: 200px; padding: 12px; border: 1px solid #ccc; }
.badge { position: absolute; top: -10px; right: -10px; background: crimson; color: #fff;
         padding: 2px 8px; border-radius: 999px; font-size: .8rem; }
</style>
<div class="produkt">
  <span class="badge">New</span>
  <h3>Headphones</h3><p>Absolutely positioned badge at the top right.</p>
</div>

position: sticky is ideal for headers and tables of contents: the element stays in the normal flow but sticks once it reaches the threshold (top: 0) – within its parent container.

<!DOCTYPE html>
<style>body{font:16px system-ui,sans-serif;margin:12px;background:#fff;color:#222}
.scroller { height: 160px; overflow: auto; border: 2px solid #999; }
.scroller h4 { position: sticky; top: 0; margin: 0; padding: 6px; background: #222; color: #fff; }
.scroller p { margin: 0; padding: 8px; }
</style>
<div class="scroller">
  <h4>A</h4><p>Anna</p><p>Aaron</p><p>Alex</p>
  <h4>B</h4><p>Ben</p><p>Bea</p><p>Bruno</p>
  <h4>C</h4><p>Cem</p><p>Clara</p><p>Chris</p>
</div>

z-index sets the stacking order – but only works on positioned elements as well as Flex/Grid items. In addition, some properties (opacity < 1, transform, filter, position: fixed, isolation: isolate) create a new stacking context: children compete for order only within that context.

<!DOCTYPE html>
<style>body{font:16px system-ui,sans-serif;margin:12px;background:#fff;color:#222}
.stapel { position: relative; height: 120px; }
.stapel div { position: absolute; width: 90px; height: 90px; color: #fff; padding: 6px; }
.rot  { background: crimson; left: 0;    top: 0;    z-index: 1; }
.blau { background: royalblue; left: 45px; top: 25px; z-index: 3; }
.gruen{ background: seagreen; left: 90px; top: 10px; z-index: 2; }
</style>
<div class="stapel">
  <div class="rot">z 1</div><div class="blau">z 3</div><div class="gruen">z 2</div>
</div>
WarningIf z-index: 9999 does not help, it is almost always due to a parent stacking context. In the DevTools, look for the ancestor with transform, opacity or its own z-index. Set z-index values as a small scale (variables like --z-modal: 100), not as an arms race.
TipAbsolute positioning is suited to overlays, badges and tooltips – not to page layout. For that you use Flexbox or Grid.