<div class="content">
  <div class="buttons">
  <button class="button" onclick="minusOne()">z-index:-1;</button> 
  <button class="button" onclick="two()">z-index:2;</button>  
  <button class="button" onclick="three()">z-index:3;</button> 
  <button class="button" onclick="four()">z-index:4;</button> 
  </div>

  <div class="example">
  <div id="square"></div>
    <div class="square2">z-index:1;</div>
    <div class="square3">z-index:2;</div>
    <div class="square4">z-index:3;</div>
  </div>
</br>
  <div class="col"><h2>CSS Code:</h2><p id="code">CSS code</p>
</div>
</div>
body {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.content {
  position: relative;
}

.buttons {
  position: relative;
  left:-200px;
  z-index:1;
}

button {
  background-color: #333;
  color: white;
  border: none;
  display: block;
  padding:5px;
  width: 100px;
  margin:5px;
  transition: .2s;
  font-weight: bold;
}

button:hover {
  background-color: white;
  color: #333;
}

.col {
  position: relative;
  font-weight: bold;
  font-size:15px;
  width: 150px;
  left:-200px;
  top:0;
}

#square {
  width: 100px;
  height:100px;
  background-color: #f2542d;
  z-index:4;
  position: absolute;
  top:0;
  left:0;
  border:3px solid #333;
}

.square2, .square3, .square4 {
  width:100px;
  height:100px;
  position: absolute;
  border:3px solid #333;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: bold;
}

.square2 {
  background-color: rgba(86, 44, 44,.5);
  top:20px;
  left:20px;
  z-index:1;
}

.square3 {
  top:40px;
  left: 40px;
  background-color: rgba(18, 116, 117, .5);
  z-index:2;
}

.square4 {
  top:60px;
  left: 60px;
  background-color: rgba(245, 223, 187,.5);
  z-index:3;
}
function minusOne() {
 document.getElementById("square").style.zIndex="-1" 
  
  var x = document.getElementById("code");
  if (x.innerHTML === "z-index:-1;") {
    x.innerHTML = "z-index:-1;";
  } else {
    x.innerHTML = "z-index:-1;";
  }
}

function two() {
 document.getElementById("square").style.zIndex="2" 
  
  var x = document.getElementById("code");
  if (x.innerHTML === "z-index:2;") {
    x.innerHTML = "z-index:2;";
  } else {
    x.innerHTML = "z-index:2;";
  }
}

function three() {
 document.getElementById("square").style.zIndex="3" 
  
  var x = document.getElementById("code");
  if (x.innerHTML === "z-index:3;") {
    x.innerHTML = "z-index:3;";
  } else {
    x.innerHTML = "z-index:3;";
  }
}

function four() {
 document.getElementById("square").style.zIndex="4" 
  
  var x = document.getElementById("code");
  if (x.innerHTML === "z-index:4;") {
    x.innerHTML = "z-index:4;";
  } else {
    x.innerHTML = "z-index:4;";
  }
}

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.