Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   
   HTML   
   CSS   
   JAVA SCRIPT   
   JQUERY   




CSS - Z-Index


The z-index property in CSS is used to specify the stack order of an element.


Sounds tough?


Let us clear with the below example.


Z-index property in CSS


The Z-index property contains numeric values. Based on the value of z-index property, an element can overlap other element.


Just remember, z-index works only on positioned elements(i.e. position: absolute, position: relative, position: fixed and position: sticky) and flex elements.


Example :



<html>
<head>
	<style>
   		.index1 {
      		position: absolute;
      		height: 250px;
      		width: 360px;
      		background-color: Violet;
      		z-index: 1;
      		text-align: center;
      		padding: 3px;
      		left: 20px;
      		top: 20px;
   		}
   		.index2 {
      		position: absolute;
      		height: 190px;
      		width: 300px;
      		background-color: Orange;
      		z-index: 2;
      		text-align: center;
      		padding: 5px;
      		left: 40px; 
      		top: 40px;
   		}
   		.index3 {
      		position: absolute;
      		height: 130px;
      		width: 250px;
      		background-color: Cornsilk;
      		z-index: 3;
      		text-align: center;
      		padding: 5px;
      		left: 60px; 
      		top: 60px;
   		}

</style>
</head>
<body>
   <div class="index1">
      z-index value 1
   </div>
   <div class="index2">
      z-index value 2
   </div>
   <div class="index3">
      z-index value 3
   </div>
</body>
</html>


Output :




In the above example, we have three <div> elements with z-index values as 1, 2 and 3. And the position property is set to absolute.


And if you see the above output, the <div> element with z-index 3 is displayed at the front, overlapping the other two.


And the <div> element with z-index 2 is displayed after z-index 3.


Similarly, the <div> element with z-index 1 is displayed after z-index 2 and z-index 3.