Skip to main content

Command Palette

Search for a command to run...

🔢 CSS z-index: Mastering the Stack Order of Elements

Published
4 min read
🔢 CSS z-index: Mastering the Stack Order of Elements
P
Hi there, tech enthusiasts! I'm a passionate Software Developer driven by a love for continuous learning and innovation. I thrive on exploring new tools and technologies, pushing boundaries, and finding creative solutions to complex problems. What You'll Find Here On my Hashnode blog, I share: 🚀 In-depth explorations of emerging technologies 💡 Practical tutorials and how-to guides 🔧Insights on software development best practices 🚀Reviews of the latest tools and frameworks 💡 Personal experiences from real-world projects. Join me as we bridge imagination and implementation in the tech world. Whether you're a seasoned pro or just starting out, there's always something new to discover! Let’s connect and grow together! 🌟

In the world of web design, what appears "on top" of what can make or break the user experience. Whether you're working with modals, tooltips, dropdowns, or overlapping images — the z-index property in CSS plays a crucial role.

This article explains everything you need to know about z-index — from beginner basics to deep-level concepts with real-life examples, best practices, and a full project code demo.


🧠 What is z-index in CSS?

z-index is a CSS property that controls the stacking order of elements along the Z-axis — the axis perpendicular to the screen (i.e., front-to-back).

✨ In Simple Words:

The higher the z-index number, the closer the element appears to the viewer (i.e., it appears "on top" of others).

.box {
  position: absolute;
  z-index: 10;
}

❗Important Rule:

z-index only works on positioned elements, meaning elements with:

  • position: relative;

  • position: absolute;

  • position: fixed;

  • position: sticky;

If an element has position: static; (default), z-index won’t work on it.


📦 How z-index Works: The Stacking Context

A stacking context is like a container in which elements stack relative to each other.

Each stacking context has its own z-index scale.

Stacking contexts are created when:

  • A positioned element has a z-index value other than auto.

  • Some CSS properties (like opacity < 1, transform, filter, perspective) are applied.


🔢 Examples of z-index Values

.modal {
  position: fixed;
  z-index: 1000;
}

.navbar {
  position: sticky;
  z-index: 999;
}

🧠 Higher number = Higher priority on the screen


📊 Real-Life Examples

1️⃣ Dropdown Menu over Page Content

.dropdown {
  position: absolute;
  z-index: 100;
}

✅ The dropdown menu should appear above all sections when clicked.


2️⃣ Modal Popup on Top of Everything

.modal {
  position: fixed;
  z-index: 9999;
}

✅ The modal covers the entire screen and stays on top.


3️⃣ Tooltip over Button

.button {
  position: relative;
  z-index: 1;
}

.tooltip {
  position: absolute;
  z-index: 10;
}

✅ Tooltip shows above the button because it has a higher z-index.


📌 Visual Concept

Imagine 3 cards stacked on a table. You want the red card to appear on top. You assign it a higher z-index. That’s exactly how it works on screen too!


❎ Common Mistakes to Avoid

MistakeWhy It HappensFix
z-index not workingElement has position: staticAdd position: relative/absolute
Still not visible on topNested stacking contextCheck parent elements' z-index and context
Overlapping UINo control over stack orderUse consistent z-index strategy

✅ Pros and ❌ Cons

✅ Pros:

  • Controls visual layering

  • Helps in designing complex UI like modals, dropdowns, tooltips

  • Essential for good UX/UI design

❌ Cons:

  • Can cause debugging issues if used without stacking context knowledge

  • Overusing high z-index values leads to messy code

  • Doesn’t work without position


🧪 Final Full Project Example: Modal on Top of Overlay

💡 Objective:

Create a layout where a modal pops up above an overlay, which is above the content.

✅ Output:

  • Content

  • Dark transparent overlay

  • Modal in center with highest z-index


💻 Full HTML + CSS + JS Code

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Z-Index Demo</title>
  <style>
    body {
      margin: 0;
      font-family: Arial, sans-serif;
    }

    .content {
      padding: 50px;
    }

    .overlay {
      display: none;
      position: fixed;
      top: 0; left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.6);
      z-index: 1000;
    }

    .modal {
      display: none;
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 300px;
      padding: 20px;
      background: white;
      border-radius: 8px;
      z-index: 1100;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
    }

    .show {
      display: block;
    }

    .btn {
      padding: 10px 20px;
      background: #007bff;
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
    }

    .close-btn {
      margin-top: 10px;
      background: red;
    }
  </style>
</head>
<body>

  <div class="content">
    <h1>Welcome to the Page</h1>
    <p>This is your main page content. Click below to open a modal.</p>
    <button class="btn" onclick="openModal()">Open Modal</button>
  </div>

  <div class="overlay" id="overlay"></div>

  <div class="modal" id="modal">
    <h2>Modal Title</h2>
    <p>This modal appears on top of everything else.</p>
    <button class="btn close-btn" onclick="closeModal()">Close</button>
  </div>

  <script>
    function openModal() {
      document.getElementById('overlay').classList.add('show');
      document.getElementById('modal').classList.add('show');
    }

    function closeModal() {
      document.getElementById('overlay').classList.remove('show');
      document.getElementById('modal').classList.remove('show');
    }
  </script>

</body>
</html>

📝 Recap

  • z-index controls stacking order (front-to-back).

  • Works only on positioned elements.

  • Use consistent and scalable z-index values in large apps.

  • Know when stacking context is created to avoid confusion.


🎯 Pro Tips

  • Use ranges like 100, 200, 300 for flexibility.

  • Don’t hardcode values like 999999 unless absolutely necessary.

  • Avoid using z-index as a quick fix — understand the structure.


If this article helped you understand z-index, don’t forget to save it for later and share it with your fellow developers. ✅

Basic to Advance : CSS

Part 13 of 15

The "Basic to Advance: CSS" series covers CSS fundamentals to advanced techniques. Learn styling, layouts, animations, and responsiveness to build modern, visually appealing websites. Perfect for beginners and developers.

Up next

🎞️ CSS animation: A Complete Guide with Real-Life Examples

Animations are everywhere — from smooth button effects to moving banners and interactive loaders. With CSS, you can create beautiful, engaging animations without a single line of JavaScript. This guide will help both freshers understand from scratch ...

More from this blog

T

Technologies: Tools & Tips | Expert Guides on Latest Tech Tools

125 posts