How To Set Z-index using CSS?

By | July 7, 2022

The z-index property specifies the stack order of an element.

The z-index Property

When elements are positioned, they can overlap other elements.

The z-index property specifies the stack order of an element (which element should be placed in front of, or behind, the others).

An element can have a positive or negative stack order:

Because the image has a z-index of -1, it will be placed behind the text.

Example

<!DOCTYPE html>
<html>
<head>
<style>
img {
  position: absolute;
  left: 0px;
  top: 0px;
  z-index: -1;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<img src="img_tree.png">
<p>Because the image has a z-index of -1, it will be placed behind the text.</p>
</body>
</html>

Result:

Another z-index Example

Example

Here we see that an element with greater stack order is always above an element with a lower stack order:<html>
<head>
<style>
.container {
  position: relative;
}

.black-box {
  position: relative;
  z-index: 1;
  border: 2px solid black;
  height: 100px;
  margin: 30px;
}

.gray-box {
  position: absolute;
  z-index: 3;
  background: lightgray;
  height: 60px;
  width: 70%;
  left: 50px;
  top: 50px;
}

.green-box {
  position: absolute;
  z-index: 2;
  background: lightgreen;
  width: 35%;
  left: 270px;
  top: -15px;
  height: 100px;
}
</style>
</head>
<body>

<div class=”container”>
  <div class=”black-box”>Black box</div>
  <div class=”gray-box”>Gray box</div>
  <div class=”green-box”>Green box</div>
</div>

</body>
</html>

Result:

Without z-index

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

Example

Same example as above, but here with no z-index specified:<html>
<head>
<style>
.container {
  position: relative;
}

.black-box {
  position: relative;
  border: 2px solid black;
  height: 100px;
  margin: 30px;
}

.gray-box {
  position: absolute;
  background: lightgray;
  height: 60px;
  width: 70%;
  left: 50px;
  top: 50px;
}

.green-box {
  position: absolute;
  background: lightgreen;
  width: 35%;
  left: 270px;
  top: -15px;
  height: 100px;
}
</style>
</head>
<body>

<div class=”container”>
  <div class=”black-box”>Black box</div>
  <div class=”gray-box”>Gray box</div>
  <div class=”green-box”>Green box</div>
</div>

</body>
</html>

Result:

Category: CSS

Leave a Reply

Your email address will not be published. Required fields are marked *