The HTML DOM style zIndex property returns and modify the stacking order of a positioned element in an HTML document.
Syntax
Following is the syntax −
Returning zIndex
object.style.zIndex
Modifying zIndex
object.style.zIndex = “value”
Values
Here, value can be −
Value | Explanation |
---|---|
initial | It set this property value to its default value. |
inherit | It inherits this property value from its parent element. |
auto | In it the elements stack in the order based on their order in the HTML document. |
number | It represents an integer that specifies the stack order of an element. |
Example
Let us see an example of HTML DOM style zIndex property −
<!DOCTYPE html> <html> <head> <style> body { color: #000; height: 100vh; } .box1 { width: 100px; height: 100px; background: lightcoral; position: relative; top: 50px; } .box2 { width: 100px; height: 100px; background: lightgreen; position: relative; } .btn { background: #db133a; border: none; height: 2rem; border-radius: 2px; width: 40%; display: block; color: #fff; outline: none; cursor: pointer; margin: 1rem 0; } </style> </head> <body> <h1>DOM Style zIndex Property Example</h1> <div class='box1'></div> <div class='box2'></div> <button onclick="add()" class="btn">Change zIndex</button> <script> function add() { document.querySelector('.box1').style.zIndex = "1"; } </script> </body> </html>
Output
This will produce the following output −
Click on “Change zIndex” button to change the order of red and green box −