Skip to content
Justice Tech School

Position and z-index

position: static is the default. relative keeps the element in the flow but lets you nudge it with top, left and so on, and makes it a reference for children. absolute removes it from the flow and places it relative to the nearest positioned ancestor. fixed sticks to the viewport, and sticky switches between relative and fixed as you scroll.

When positioned elements overlap, z-index decides the stacking: higher numbers sit on top. It only works on positioned elements (and flex or grid items).

Example
<style>
  .wrap { position: relative; height: 140px; background: #e2e8f0; }
  .badge { position: absolute; top: 8px; right: 8px; background: #dc2626; color: white; padding: 4px 10px; border-radius: 999px; z-index: 2; }
  .under { position: absolute; top: 30px; left: 30px; width: 120px; height: 80px; background: #38bdf8; z-index: 1; }
</style>
<div class="wrap">
  <div class="under">Beneath</div>
  <div class="badge">New</div>
</div>
  • Give the parent position: relative so the absolute child stays inside it.

Exercise

Position the badge relative to its nearest positioned parent.

.badge {
  position: ;
  top: 0;
  right: 0;
}

Quiz Test

An absolute element is placed relative to:

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.