CSS Tutorial

Introduction

Edit Template

CSS Tutorial

Introduction

Edit Template

CSS z-index

When several elements on a webpage overlap, which one appears on top? That’s where z-index comes in. It controls the stacking order — the higher the z-index value, the closer the element is to the viewer.

What is z-index?

Think of your webpage like layers of paper stacked on top of each other. The element with the highest z-index sits on top of all others. This is especially useful when you’re dealing with positioned elements like absolute, relative, or fixed.

Example:

				
					<!DOCTYPE html>
<html>
<head>
  <title>Learn With Arshyan – z-index Demo</title>
  <style>
    .wrapper {
      position: relative;
    }

    .layer-one {
      position: relative;
      z-index: 1;
      background-color: lightblue;
      border: 2px solid black;
      height: 100px;
      margin: 40px;
    }

    .layer-two {
      position: absolute;
      z-index: 3;
      background-color: salmon;
      width: 65%;
      height: 70px;
      left: 220px;
      top: 40px;
      border: 2px solid black;
    }

    .layer-three {
      position: absolute;
      z-index: 2;
      background-color: indigo;
      color: #fff8dc;
      width: 40%;
      height: 90px;
      left: 240px;
      top: 20px;
      border: 2px solid black;
    }
  </style>
</head>
<body>

  <h1>Understanding CSS z-index – Learn With Arshyan</h1>

  <div class="wrapper">
    <div class="layer-one">Layer 1 (z-index: 1)</div>
    <div class="layer-two">Layer 2 (z-index: 3)</div>
    <div class="layer-three">Layer 3 (z-index: 2)</div>
  </div>

</body>
</html>

				
			
Z-index Example

Explanation

  • Layer 2 has the highest z-index: 3, so it appears on top of all others.

  • Layer 3 comes next with z-index: 2.

  • Layer 1 has the lowest priority (z-index: 1) and appears at the back.

 If you don’t use z-index, the browser simply displays elements in the order they appear in the HTML — meaning the last element will cover earlier ones if they overlap.

Quick Tip – When to Use z-index

Always pair z-index with a positioned element (relative, absolute, fixed, or sticky).
Without positioning, z-index won’t work.

 

Mastering z-index helps you build cleaner, layered layouts — whether you’re creating dropdowns, modals, sliders, or tooltips. It’s one of the simplest yet most powerful tools in your CSS toolbox.

Scroll to Top