CHAPTER 23

CSS Z-index

Learn how z-index controls which positioned element appears in front of another element.

01. What is CSS Z-index?

z-index controls the stacking order of overlapping elements.
An element with a higher z-index generally appears above an element with a lower z-index.
It is commonly used with position properties.

02. Syntax

selector { position: relative; z-index: number; }

03. Example

CSS / HTML Example AIFA Coding Lab
<!DOCTYPE html>
<html>
<head>

<style>

.box1 {

    position: absolute;

    width: 180px;

    height: 180px;

    background: #2563eb;

    z-index: 1;

}

.box2 {

    position: absolute;

    top: 60px;

    left: 60px;

    width: 180px;

    height: 180px;

    background: #ec4899;

    z-index: 2;

}

</style>

</head>

<body>

<div class="box1"></div>

<div class="box2"></div>

</body>
</html>

04. Important Points

✓ Higher z-index values can place elements above lower values.
✓ z-index works in the context of stacking and positioned elements.
✓ Use meaningful z-index values instead of randomly using very large numbers.
✓ Stacking contexts can affect z-index behavior.

05. Common Mistakes

⚠ Using z-index: 999999 everywhere.
⚠ Forgetting that stacking contexts can change how z-index behaves.
⚠ Using z-index when the real problem is incorrect positioning.

06. Real World Use

z-index is used for dropdown menus, modal windows, navigation bars, popups, overlays and floating UI elements.

Ready to Practice? 🚀

Open the AIFA CSS Editor and practice this chapter live.

Try It Yourself →
Practice Exercise

Create Overlapping Boxes

Create three overlapping boxes and use z-index values 1, 2 and 3 to control their stacking order.