CSS

CSS (Cascading Style Sheets) is the language that brings web pages to life with colors, layouts, and animations. It works alongside HTML to create visually stunning and responsive designs. Let's explore the power of CSS.

CSS Z-index

31 March 2025 | Category:

The z-index property in CSS is used to control the stack order of elements. It determines which element appears on top when elements overlap.


1️⃣ Syntax

selector {
    position: relative | absolute | fixed | sticky;
    z-index: value;
}

Possible Values

ValueDescription
autoDefault. The element follows the stacking order.
numberHigher numbers appear on top of lower ones.
negativeElements with negative z-index appear behind others.

⚠️ z-index only works on positioned elements (relative, absolute, fixed, or sticky).
⚠️ z-index does NOT work on elements with position: static.


2️⃣ How z-index Works

Elements are stacked in the following order (from bottom to top):

  1. Background (default elements)
  2. Elements with position: static
  3. Elements with position: relative
  4. Elements with position: absolute
  5. Elements with position: fixed
  6. Elements with z-index (higher values appear on top)

3️⃣ Example: Basic z-index Usage

.box1 {
    position: absolute;
    top: 50px;
    left: 50px;
    width: 100px;
    height: 100px;
    background: red;
    z-index: 1; /* Lower priority */
}

.box2 {
    position: absolute;
    top: 70px;
    left: 70px;
    width: 100px;
    height: 100px;
    background: blue;
    z-index: 2; /* Higher priority (appears on top) */
}

Result: The blue box appears on top of the red box because z-index: 2 is greater than z-index: 1.


4️⃣ Negative z-index (Behind Other Elements)

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

Use Case: Place an element behind other elements (like background decorations).


5️⃣ z-index with Parent Elements

If a parent has z-index: 1 and a child has z-index: 999, the child cannot escape its parent’s stacking order.

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

.child {
    position: absolute;
    z-index: 999; /* Still inside parent, can't go above other elements outside */
}

6️⃣ z-index in Practical Use Cases

Dropdown Menu Above Everything

.menu {
    position: absolute;
    z-index: 1000; /* Ensures it's above all elements */
}

Modal (Popup) on Top

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

Sticky Header Above Content

.header {
    position: sticky;
    top: 0;
    z-index: 100;
}

🎯 Summary

z-index ValueEffect
autoDefault stacking order.
Positive z-indexElement moves on top of lower values.
Negative z-indexElement moves behind other elements.
z-index inside parentA child’s z-index is limited by the parent’s z-index.

💡 Use z-index wisely to control stacking order! 🚀