The zIndex property sets or returns the stack order of a positioned element.
An element with greater stack order (1) is always in front of another element with lower stack order (0).
A positioned element is an element with the position property set to: relative, absolute, or fixed.
This property is useful if you want to create overlapping elements.
Syntax and Usage
Return the zIndex property: object.style.zIndex Set the zIndex property: object.style.zIndex = "auto|number|initial|inherit"
Property Values
Value | Description |
---|---|
auto | The browser determines the stack order of the element (based on its order in the document). This is default |
number | An integer that defines the stack order of the element. Negative values are allowed |
initial | Sets this property to its default value. |
inherit | Inherits this property from its parent element. |
Example(1)
<img id="img1" src="../image/demo1.jpg" width="200" height="200"> <button class="btn btn-success" type="button" onclick="move1_function()">Change stack order</button> <script> function move1_function() { document.getElementById("img1").style.zIndex = "1"; } </script>
<img id="img1" src="../image/demo1.jpg" width="200" height="200"> <button class="btn btn-success" type="button" onclick="move2_function()">Change stack order</button> <script> function move1_function() { document.getElementById("img1").style.zIndex = "1"; } function move2_function() { alert(document.getElementById("img1").style.zIndex); } </script>
In above example when you click button it will return the z-index property value of an <img> element
Complete code for CSS Style ZIndex Properties With JavaScript
<!DOCTYPE html> <html> <head> <title>Use CSS Style ZIndex Properties With JavaScript</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> </head> <style> h1 { color: red; } #img1 { position: absolute; left: 0px; top: 0px; z-index: -1 } </style> <body> <div class="container"> <br> <br> <div class="text-center"> <h1>Use CSS Style ZIndex Properties With JavaScript</h1> </div> <br> <div class="col-md-4"> <img id="img1" src="../image/demo1.jpg" width="200" height="200"> <button class="btn btn-success" type="button" onclick="move1_function()">Change stack order</button> </div> <div class="col-md-4"> <img id="img1" src="../image/demo1.jpg" width="200" height="200"> <button class="btn btn-success" type="button" onclick="move2_function()">Change stack order</button> </div> </body> </html> <script> function move1_function() { document.getElementById("img1").style.zIndex = "1"; } function move2_function() { alert(document.getElementById("img1").style.zIndex); } </script>