Javascript Reference - HTML DOM Style zIndex Property








The zIndex property sets or get the stack order of a positioned element.

An element with greater z-index is always in front of another element with lower z-index.

Browser Support

zIndex Yes Yes Yes Yes Yes

Syntax

Return the zIndex property:

var v = object.style.zIndex 

Set the zIndex property:

object.style.zIndex='auto|number|initial|inherit'




Property Values

ValueDescription
auto Set the stack order equal to its parents. This is default
number Set the stack order. Negative numbers are allowed
inherit Inherit the z-index from the parent element

Technical Details

Default Value: auto
Return Value: A string representing the z-index
CSS Version CSS2




Example

The following code shows how to change the stack order of an <img> element


<!DOCTYPE html>
<html>
<head>
<style>
#img1 {<!--from  w  ww. ja  v a2  s  .  c o m-->
    position: absolute;
    left: 0px;
    top: 0px;
    z-index: -1
}
</style>
</head>
<body>
<h1>This is a Heading</h1>
<img id="img1" src="http://java2s.com/style/demo/border.png" width="100" height="180">
<button type="button" onclick="myFunction()">test</button>
<script>
function myFunction() {
    document.getElementById("img1").style.zIndex = "1";
}
</script>

</body>
</html>

The code above is rendered as follows:

Example 2

The following code shows how to change the z-index property value of an <div> element.


<!DOCTYPE html>
<html>
<head>
<style> 
#myDIV {<!--   w w  w  . j  ava 2  s  .c  om-->
    position: absolute;
    width: 300px;
    height: 150px;
    background-color: lightblue;
    border: 1px solid black;
}

#DIV2 {
    position: relative;
    top: 130px;
    left: 30px;
    width: 300px;
    height: 150px;
    background-color: coral;
    border: 1px solid black;
}
</style>
</head>
<body>
<button onclick="myFunction()">test</button>
<div id="DIV2">hi</div>
<div id="myDIV"></div>
<script>
function myFunction() {
    document.getElementById("myDIV").style.zIndex = "-1";
}
</script>
</body>
</html>

The code above is rendered as follows:

Example 3

The following code shows how to get the z-index property value of an <img> element


<!DOCTYPE html>
<html>
<body>
<!--from   w w w. j  a va 2  s  .c  o  m-->
<h1>This is a Heading</h1>

<img id="img1" src="http://java2s.com/style/demo/border.png" style="position:absolute;left:0px;top:0px;z-index:-1;width:100px;height:180px;">

<button type="button" onclick="myFunction()">test</button>
<script>
function myFunction() {
    console.log(document.getElementById("img1").style.zIndex);
}
</script>

</body>
</html>

The code above is rendered as follows: