0
0
CssConceptBeginner · 3 min read

What is z-index in CSS: Simple Explanation and Examples

The z-index property in CSS controls the stacking order of elements on a webpage. Elements with a higher z-index appear in front of those with a lower value when they overlap. It only works on positioned elements like relative, absolute, or fixed.
⚙️

How It Works

Imagine you have several transparent sheets stacked on top of each other. Each sheet has some drawings, and you want to decide which drawing appears on top when they overlap. The z-index property in CSS works like the order of these sheets.

Elements with a higher z-index value are like sheets placed above others, so they appear in front. If two elements have the same z-index, the one that comes later in the HTML code will appear on top.

Note that z-index only works on elements that have a position other than static (the default). This means you must set position to relative, absolute, or fixed for z-index to take effect.

💻

Example

This example shows three colored boxes overlapping. The box with the highest z-index appears on top.

html
html, body {
  height: 100%;
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 1rem;
}
.box {
  width: 100px;
  height: 100px;
  position: relative;
  opacity: 0.8;
}
.red {
  background-color: red;
  z-index: 1;
}
.green {
  background-color: green;
  z-index: 3;
}
.blue {
  background-color: blue;
  z-index: 2;
}

<div class="box red"></div>
<div class="box green"></div>
<div class="box blue"></div>
Output
Three overlapping squares: red behind, blue in the middle, and green on top.
🎯

When to Use

Use z-index when you want to control which elements appear above others on your webpage. This is common in menus, pop-ups, modals, tooltips, or any layered design.

For example, if you have a dropdown menu, you want it to appear above other content. Setting a higher z-index on the menu ensures it is visible on top.

Also, when elements overlap unintentionally, adjusting z-index can fix which one should be in front.

Key Points

  • Only works on positioned elements: Set position to relative, absolute, or fixed.
  • Higher value means front: Elements with bigger z-index appear above others.
  • Default stacking: Without z-index, elements stack in HTML order.
  • Negative values allowed: You can use negative z-index to send elements behind.

Key Takeaways

The z-index property controls which overlapping element appears on top.
It only works on elements with a position other than static.
Higher z-index values bring elements forward in the stacking order.
Use z-index to manage layering in menus, pop-ups, and overlapping content.