Categories
Web development

CSS z-index Property


The CSS z-index property sets the stack order of an element. An element with higher stack order is always on the top of an element with a lower stack order.

CSS z-index Property

The CSS z-index property only works on positioned elements (position: absolute, position: relative, position: sticky, position: fixed) and flex items (elements that are direct children of display:flex elements).

Demo:

Syntax:

z-index: auto|number;

auto (default) – settles the stack order equal to its parents.

number – settles the stack order of the element (negative numbers are allowed).

Example1:

<!DOCTYPE html>
<html>
<head>
<style>
  .ex-1 {
    position: relative;
  }
  
  .square-1, .square-2, .square-3 {
    position: absolute;
    width:100px;
    height: 100px;
    border:3px solid #333;
    color: white;
  }
  
  .square-1 {
    top:0;
    left:0;
    background-color: #264653;
    z-index:2;
  }
 
  .square-2 {
    left:25px;
    top: 25px;
    background-color: #e76f51;
    z-index:3;
  }
  
  .square-3 {
    left: 50px;
    top:50px;
    background-color: #2a9d8f;
    z-index:1;
  }
</style>
</head>
<body>

<div class="ex-1">
  <div class="square-1">z-index:2;</div>
  <div class="square-2">z-index:3;</div>
  <div class="square-3">z-index:1;</div>
  </div>

</body>
</html>

Output:

z-index:2;
z-index:3;
z-index:1;




Example2:

<!DOCTYPE html>
<html>
<head>
<style>

.example {
    position: relative;
    width:320px;
    height: 240px;
}
  
img {
  position: absolute;
  left: 0;
  top: 0;
  z-index:-1;
}

p { position: absolute;
    color: white;
    transform: translate(-50%, -50%);
    text-align: center;
    left:50%;
    top:45%;
  }

</style>
</head>
<body>

<div class="example">
<p>CSS</br>z-index</br>Property</p>
<img src="https://lenadesign.org/wp-content/uploads/2022/02/heart-shape-adobe-illustrator.jpg" width="320" height="auto">
</div>

</body>
</html>

Output:

CSS
z-index
Property


Note: If two positioned elements overlap without a z-index defined, the element placed last in the HTML code will be shown on top.

Enjoy coding!

Read also:

CSS overflow Property

CSS text-decoration Property

CSS padding Property