पाठ 9 / 25

Positioning and Layering

Relative, absolute, fixed, sticky.

Place elements over others

relative on a parent and absolute on a child positions the child with top-0, right-2 or inset-0. fixed attaches to the viewport (modals, toasts) and sticky top-0 keeps headers visible while scrolling within their container. z-10, z-50 control stacking order. overflow-hidden clips children, and isolate creates a new stacking context so z-index values do not leak.

A badge on an icon and a sticky header

Positioning patterns.

<button class="relative p-2" aria-label="Notifications, 3 unread">
  <svg class="size-6" aria-hidden="true">...</svg>
  <span class="absolute -top-1 -right-1 grid size-5 place-items-center rounded-full bg-red-600 text-xs text-white">3</span>
</button>

<header class="sticky top-0 z-40 border-b bg-white/80 backdrop-blur">...</header>

Keep a small z-index scale

Use a few agreed levels (dropdowns, sticky headers, modals) instead of ever-larger numbers.

त्वरित जाँच: What must the parent usually have for an absolute child to position relative to it?

  • overflow-auto
  • flex
  • relative (or another non-static position)
  • z-0 only
Answer

relative (or another non-static position) — Absolute positions against the nearest positioned ancestor.