CSS Tutorial 0/203 lessons ~6 min read Lesson 26

    CSS Z-index

    css z-index z-index controls stacking order — which element renders on top when they overlap. it only works on positioned

    Course progress0%
    Focus
    26 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    z-index controls stacking order — which element renders on top when they overlap. It only works on positioned elements (and on flex/grid items).

    Business problem

    Business pressure: Product teams need z-index and stacking contexts implemented consistently — layout regressions, WCAG failures, and LCP/CLS cliffs on Amazon-scale surfaces directly hit conversion and brand trust.

    • Conversion: Visual polish and render performance on z-index and stacking contexts surfaces affect checkout and signup funnels at Shopify.
    • Brand: Inconsistent z-index and stacking contexts fragments Material Design design-system contracts across squads.
    • Velocity: CSS debt around z-index and stacking contexts slows every feature team — staff engineers treat styling as platform infrastructure.

    Why this feature exists

    Platform history: CSS standardized z-index and stacking contexts so authors could separate presentation from HTML without table-layout hacks or per-element JavaScript layout engines.

    • Problem solved: Declarative, cacheable styling for z-index and stacking contexts across entire sites and design systems.
    • Rejected alternative: Inline styles and JS layout — unmaintainable at Amazon product scale.

    Browser rendering perspective

    Rendering impact: CSS Z-index touches the style → layout → paint → composite pipeline differently per engine when z-index and stacking contexts rules change.

    • Chrome (Blink): Style invalidation → LayoutNG → Paint → Viz compositor; properties used in z-index and stacking contexts may trigger layout-only or paint-only invalidation.
    • Firefox (Gecko): Servo Stylo resolves cascade; WebRender composites — subpixel z-index and stacking contexts rounding can differ from Blink.
    • Safari (WebKit): WebKit style resolver + GPU layer rules; z-index and stacking contexts bugs often surface only on iOS Safari — validate on real devices.

    Internal browser workflow

    Workflow: DOM + CSSOM → selector matching for z-index and stacking contexts rules → cascade/specificity → computed values → layout tree → paint → composite.

    • Matching cost: Overly broad selectors for z-index and stacking contexts increase style recalc on large Shopify product DOMs.
    • Cascade: Source order, specificity, and inheritance pick winning z-index and stacking contexts declarations.
    • DevTools: Computed tab shows final z-index and stacking contexts values — diff across Chrome, Firefox, and Safari.

    Feature deep dive

    Things to know:

    • Higher z-index = closer to the viewer.
    • Default is auto (~0); negative values go behind.
    • z-index only works on positioned elements (relative, absolute, fixed, sticky).
    • Stacking contexts — opacity < 1, transform, filter, and others create new contexts. A child with z-index: 9999 still can't escape its parent context.

    Examples

    A modal overlay system using a small set of layered z-indexes:

    css
    :root {
    --z-dropdown: 100;
    --z-sticky: 200;
    --z-modal: 1000;
    --z-toast: 2000;
    }
    .modal { position: fixed; inset: 0; z-index: var(--z-modal); }

    Real-world use

    When a modal appears under a header you didn't expect, it's almost always a stacking context bug — the header has transform or filter and trapped its z-index.

    Real production example

    Production: Amazon, Shopify, and Shopify codify z-index and stacking contexts via design tokens, Stylelint, visual regression CI, and component prop APIs aligned with Material Design.

    • Pattern: Token-driven z-index and stacking contexts with Percy/Chromatic snapshots on every PR.
    • Observability: CrUX/RUM tie z-index and stacking contexts changes to LCP and CLS on high-traffic templates.
    • Contract: Design system documents allowed values — no rogue hex in product CSS.

    Enterprise use case

    Enterprise: Polaris, Carbon, and Material Design encode z-index and stacking contexts in multi-brand token pipelines, dark mode, and white-label tenant themes.

    • Component APIs: Apps consume z-index and stacking contexts via tokens and props — not ad-hoc stylesheets.
    • CI gates: axe, contrast checks, and Coverage audits block z-index and stacking contexts regressions before merge.
    • Migration: Legacy z-index and stacking contexts refactors use codemods plus visual diff baselines.

    Accessibility considerations

    A11y: z-index and stacking contexts must not remove focus visibility, break 200% zoom, convey state by color alone, or hide content from assistive technology (WCAG 2.2).

    • Focus: :focus-visible + outline — never naked outline: none.
    • Contrast: Verify z-index and stacking contexts color choices meet 4.5:1 on Shopify checkout and form flows.
    • Motion: Gate z-index and stacking contexts animations behind prefers-reduced-motion.

    Performance considerations

    Performance: z-index and stacking contexts can trigger reflow, expensive selectors, compositor layer explosion, or unused CSS bloat — profile with DevTools Performance and Coverage.

    • Animation: Animate transform/opacity for z-index and stacking contexts — avoid layout-thrashing properties.
    • Selectors: Deep chains for z-index and stacking contexts slow style recalc on Amazon-size pages.
    • Payload: Purge unused z-index and stacking contexts rules in production bundles (Tailwind JIT, PurgeCSS).

    SEO considerations

    SEO: z-index and stacking contexts affects LCP, CLS, and mobile usability — Google Core Web Vitals and readable above-the-fold content are ranking signals.

    • LCP: z-index and stacking contexts on hero type and images determines largest contentful paint timing.
    • CLS: Reserve space with sizing (z-index and stacking contexts) before fonts and images load.
    • Mobile: Readable z-index and stacking contexts at 320px — Material Design mobile-first baseline.

    Scalability considerations

    Scale: z-index and stacking contexts choices compound across micro-frontends, A/B skins, dark mode, and Shopify multi-tenant white-label themes.

    • Tokens: Centralize z-index and stacking contexts in custom properties — not magic numbers per squad.
    • Specificity: Flat selectors scale better than nested wars across dozens of teams.
    • Theming: Polaris and Carbon theme switches depend on consistent z-index and stacking contexts architecture.

    Common production issues

    Production failures: Specificity overrides, Safari-only z-index and stacking contexts glitches, stacking contexts, and breakpoints that pass Chrome CI but fail iOS WebKit.

    • Cross-browser: Subpixel z-index and stacking contexts differs Blink vs WebKit — test real Safari.
    • Regression: Global token change breaks unrelated z-index and stacking contexts — visual CI catches it.
    • Third-party: Widget CSS collides with app z-index and stacking contexts — namespace or Shadow DOM.

    Debugging guide

    Debug: Chrome DevTools Elements (Styles + Computed), Layout/Flex/Grid overlays; Firefox layout tools; Safari Web Inspector on device.

    • Overrides: Crossed-out z-index and stacking contexts rules — trace specificity winner.
    • Box model: Inspect margin/padding/border when z-index and stacking contexts layout surprises.
    • Coverage: Find dead z-index and stacking contexts CSS bloating bundles.
    css
    /* DevTools workflow — z-index */
    1. Elements → select target node
    2. Computed → filter relevant properties
    3. Layout → box model + flex/grid overlay
    4. Performance → record scroll/interaction

    Best practices

    • Define a small z-index scale as variables — never sprinkle 9999 everywhere.
    • Understand stacking contexts before raising z-index.

    Anti-patterns

    • Inline styles: z-index and stacking contexts via style="" — unmaintainable at Amazon scale.
    • !important wars: Fixing z-index and stacking contexts with specificity nukes instead of architecture.
    • Magic numbers: Random px for z-index and stacking contexts outside the spacing/type token scale.

    Trade-offs

    • Utility vs components: Tailwind velocity vs Carbon-style token components for z-index and stacking contexts.
    • Reset vs normalize: Predictable z-index and stacking contexts baseline vs faster initial ship.
    • Pure CSS vs JS: z-index and stacking contexts without JavaScript until touch/a11y needs progressive enhancement.

    Architecture review questions

    • Which z-index and stacking contexts properties trigger layout vs paint vs composite-only updates?
    • How does this z-index and stacking contexts choice affect WCAG contrast and keyboard focus visibility?
    • What happens to z-index and stacking contexts under dark mode and Material Design design tokens?
    • Where could z-index and stacking contexts cause CLS or LCP regression on Shopify templates?
    • How would you debug overridden z-index and stacking contexts rules in production?
    • What is the migration path for z-index and stacking contexts across 20 micro-frontends?

    Interview questions

    Explain how z-index and stacking contexts interacts with the CSS cascade and specificity.(Intermediate)

    Multiple rules may target the same element. Specificity tuple (inline, ids, classes, types) picks the winner; source order breaks ties. Staff engineers keep z-index and stacking contexts selectors flat and token-driven so overrides are intentional. !important belongs in utility layers only.

    Follow-up: When would :where() reduce specificity for z-index and stacking contexts?

    How does z-index and stacking contexts render differently in Chrome, Firefox, and Safari?(Advanced)

    Cascade logic is shared but layout/paint pipelines differ: Blink LayoutNG, Gecko reflow, WebKit iOS quirks. z-index and stacking contexts involving sticky, filters, or subpixel rounding often exposes engine bugs. Validate on WebKit hardware; use @supports when needed.

    Follow-up: What creates a stacking context related to z-index and stacking contexts?

    How would Amazon or Shopify govern z-index and stacking contexts at enterprise scale?(Advanced)

    Design tokens in CSS variables, Stylelint, component APIs exposing z-index and stacking contexts props not raw classes, visual regression CI, axe in pipeline. Cross-team z-index and stacking contexts changes go through design-system RFCs. Measure CrUX after refactors on checkout paths.

    Follow-up: Trade-off: utility-first vs BEM for z-index and stacking contexts?

    Hands-on exercise

    Exercise: Implement z-index and stacking contexts on a component using Polaris spacing tokens — pass axe, Lighthouse ≥ 90, and Percy snapshots on mobile + desktop.

    • Deliverable: PR with z-index and stacking contexts CSS, token references, before/after screenshots.
    • Verify: Keyboard-only nav, 200% zoom, prefers-reduced-motion.
    • Stretch: ADR for z-index and stacking contexts token naming in your design system.

    Staff engineer notes

    • Rendering lens: Classify every z-index and stacking contexts property as layout, paint, or composite — animate composite-safe properties only.
    • Platform lens: z-index and stacking contexts belongs in the design-system layer; product teams consume tokens.
    • Measurement lens: Tie z-index and stacking contexts changes to CrUX LCP/CLS on Shopify — CSS is revenue infrastructure.

    Common pitfalls

    • Bumping z-index hoping it'll work — the real issue is usually a parent stacking context.
    • position: static elements ignore z-index.

    Try it yourself

    Edit the CSS panel — the preview updates live. Use DevTools Performance and Accessibility panels to validate.

    Try it yourself

    Preview

    Summary

    CSS Z-index is core CSS engineering. Staff engineers evaluate z-index and stacking contexts through browser pipelines (Blink, Gecko, WebKit), WCAG 2.2, and design-system contracts (Material Design, Polaris, Carbon) — scaling across Amazon-class product surfaces without layout or accessibility debt.

    Key takeaways

    • z-index only works on positioned elements.
    • Stacking contexts trap children — beware transform/opacity on parents.
    • Use a small scale, not random big numbers.
    Ready to mark this lesson complete?Track your journey across the entire course.