0
0
CSSmarkup~5 mins

Common layering issues in CSS

Choose your learning style9 modes available
Introduction

Layering helps decide which parts of a webpage appear on top of others. Sometimes layers don't show as expected, causing confusion or hiding content.

When a button is hidden behind an image and can't be clicked.
When a dropdown menu disappears behind other page elements.
When overlapping text is hard to read because layers are mixed up.
When you want to create a popup that appears above everything else.
When animations or effects don't show properly because of layer order.
Syntax
CSS
selector {
  position: relative | absolute | fixed | sticky;
  z-index: number;
}

position must be set to something other than static for z-index to work.

z-index uses numbers; higher numbers appear on top.

Examples
This element will be above elements with lower or no z-index.
CSS
div {
  position: relative;
  z-index: 1;
}
This image will appear on top of elements with lower z-index.
CSS
img {
  position: absolute;
  z-index: 10;
}
This z-index will not work because position is static by default.
CSS
button {
  position: static;
  z-index: 5;
}
Sample Program

Three colored boxes overlap. Box 2 has the highest z-index so it appears on top. Box 1 is in the middle. Box 3 has the lowest z-index and appears behind the others.

CSS
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Layering Example</title>
  <style>
    .box1 {
      position: relative;
      width: 150px;
      height: 150px;
      background-color: lightblue;
      z-index: 1;
      margin: 20px;
    }
    .box2 {
      position: relative;
      width: 150px;
      height: 150px;
      background-color: coral;
      margin: -100px 0 0 100px;
      z-index: 2;
    }
    .box3 {
      position: relative;
      width: 150px;
      height: 150px;
      background-color: lightgreen;
      margin: -100px 0 0 50px;
      z-index: 0;
    }
  </style>
</head>
<body>
  <div class="box1">Box 1 (z-index: 1)</div>
  <div class="box2">Box 2 (z-index: 2)</div>
  <div class="box3">Box 3 (z-index: 0)</div>
</body>
</html>
OutputSuccess
Important Notes

Always set position to relative, absolute, fixed, or sticky for z-index to work.

Elements with the same z-index follow the order they appear in the HTML (later elements appear on top).

Parent elements' stacking context can affect child elements' layering.

Summary

Use position and z-index to control which elements appear on top.

Higher z-index means the element is closer to the front.

Without proper position, z-index won't work.