Z Index

Exercise

  1. In the "index.html" file, replace the code with the following:
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CSS</title>
  <link rel="stylesheet" href="./css/styles.css">
</head>

<body>
  <h1>Z Index</h1>
  <div class="container">
    <div class="box-1">
      <p>By default, this div will appear at the bottom of the other two</p>
    </div>
    <div class="box-2"></div>
    <div class="box-3">
      <p>By default, this div will appear at the top of the other two</p>
    </div>
  </div>
  <div class="container">
    <div class="box-1 z-index-3">
      <p>This div has the highest z-index so it will show on top of the other two</p>
    </div>
    <div class="box-2 z-index-1">
      <p>This div has the lowest z-index so it will show on the bottom</p>
    </div>
    <div class="box-3 z-index-2"></div>
  </div>
</body>

</html>
  1. Save.
  2. If "Live Server" is not already running, right-click anywhere in the editor and select "Open with Live Server" from the context menu.
  3. In the "styles.css" file, replace the code with the following:
.container {
  border: 5px solid blue;
  padding: 10px;
  margin: 20px;
  position: relative;
  width: 80vw;
  height: 30vh;
}

.box-1 {
  width: 200px;
  height: 200px;
  background: green;
  color: white;
  position: absolute;
  top: 0;
  left: 0;
}

.box-2 {
  width: 200px;
  height: 200px;
  background: red;
  color: white;
  position: absolute;
  top: 10%;
  left: 10%;
}

.box-3 {
  width: 200px;
  height: 200px;
  background: blue;
  color: white;
  position: absolute;
  top: 20%;
  left: 20%;
}

.z-index-1 {
  z-index: 1;
}

.z-index-2 {
  z-index: 2;
}

.z-index-3 {
  z-index: 3;
}
  1. Save.
  2. In the browser, you should see the following:

  3. Exercise 2 Result

Code Walkthrough and Explanation


z-index

z-index is a CSS property that controls the vertical stacking order of elements that have been positioned on a web page using position: absolute, position: relative, or position: fixed.

By default, elements on a web page are arranged in a 2D stacking order based on the order in which they appear in the HTML code. However, when two or more elements overlap, the z-index property can be used to control which element is visually on top of the others.

The z-index property accepts a positive or negative integer value, with higher values appearing on top of lower values. Elements with a higher z-index value will appear on top of elements with a lower z-index value, and elements with the same z-index value will be arranged based on their order in the HTML code.


Experiment with the Code


Video and Code References


Questions? Subscribe and ask in the video comments:


GitHub and Other References