Element Positioning and Z-Index
Sizing and margins are not always enough to place elements. When building interfaces like header bars, drop-down menus, or absolute status bubbles, you need precise control over CSS Positioning.
1. Positioning Utilities
Tailwind provides utilities that map to the standard CSS position property:
- static (
static): Default placement according to the normal page document flow. - relative (
relative): Positioned relative to its normal placement, enabling the offset properties (top,bottom,left,right) and serving as a anchor container for absolute children. - absolute (
absolute): Positioned relative to its nearest relative parent container, escaping the standard document flow. - fixed (
fixed): Positioned relative to the browser window viewport. It remains in a fixed position even when the page scrolls. - sticky (
sticky): Behaves like a relative element until it reaches a scroll offset threshold, then sticks to its position.
2. Offset Position Coordinates
Once position is set (such as absolute or fixed), you can specify offsets using top, bottom, left, and right coordinates:
top-0,left-0: Pins the element to the top-left corner.right-4,bottom-4: Pins the element 1rem away from the bottom-right corner.inset-0: Pins the element to all four edges simultaneously (equivalent to setting top, bottom, left, and right to 0).
<!-- Relative parent container -->
<div className="relative w-64 h-32 bg-gray-100 rounded-lg">
<!-- Absolute indicator bubble pinned to top-right corner -->
<span className="absolute top-2 right-2 w-3 h-3 bg-red-600 rounded-full"></span>
</div>3. Z-Index Layer Control
When positioning elements absolute or fixed, they can overlap. The z-index property determines which element renders on top.
Tailwind provides a numeric scale for z-index values:
z-0(z-index: 0)z-10(z-index: 10)z-30(z-index: 30)z-50(z-index: 50, commonly used for navigation header bars)z-auto(z-index: auto)
<!-- Fixed Navigation header pinned on top of page content -->
<header className="fixed top-0 left-0 w-full h-16 bg-white shadow-md z-50">
Navigation Header Content
</header>Published on Last updated: