TechLead

Positioning, Display, and Z-Index

Control layout flow, stacking, and element placement

Display Types

The display property controls how elements participate in layout. Understanding block, inline, and inline-block is essential before moving to advanced layouts.

/* Block: takes full width, starts on new line */
div { display: block; }

/* Inline: fits content, does not break line */
span { display: inline; }

/* Inline-block: inline flow + width/height */
.badge { display: inline-block; padding: 4px 10px; }

/* Hide element */
.hidden { display: none; }

Positioning Basics

Relative

Moves the element from its normal position, but still takes space.

.box {
  position: relative;
  top: 10px;
  left: 20px;
}

Absolute

Removed from flow; positioned relative to nearest positioned ancestor.

.parent { position: relative; }
.child {
  position: absolute;
  top: 0;
  right: 0;
}

Fixed

Stays in place relative to the viewport.

.floating {
  position: fixed;
  bottom: 16px;
  right: 16px;
}

Sticky

Scrolls until it hits a threshold, then sticks.

header {
  position: sticky;
  top: 0;
}

Z-Index & Stacking Context

z-index controls stacking order, but it only works on positioned elements. New stacking contexts can change how elements overlap.

.card { position: relative; z-index: 2; }
.overlay { position: absolute; z-index: 10; }

/* Creates stacking context */
.modal {
  position: relative;
  z-index: 100;
  transform: translateZ(0);
}
  • ✓ Only positioned elements respond to z-index.
  • ✓ Properties like transform, opacity, and filter create new stacking contexts.
  • ✓ When in doubt, check which ancestor created the stacking context.

Containing Blocks & Inset

Absolute positioning is calculated relative to the nearest ancestor that is positioned (relative, absolute, fixed, or sticky).

.parent { position: relative; }
.child {
  position: absolute;
  inset: 12px; /* shorthand for top/right/bottom/left */
}

Sticky Positioning Rules

position: sticky only works when you set a threshold like top. It also respects the scroll container—if a parent has overflow: hidden, the sticky element won't stick beyond it.

.section-title {
  position: sticky;
  top: 16px;
  background: white;
}

⚠️ Positioning Pitfalls

  • ❌ Absolutely positioned elements ignore normal flow
  • ❌ Missing top/right/bottom/left means no visible change
  • ❌ Unexpected stacking due to new stacking contexts