Javascript Reference - HTML DOM Style opacity Property








The opacity property sets or gets the opacity level of an element.

Browser Support

Style opacity Yes Yes Yes Yes Yes

Syntax

Return the opacity property:

var v = object.style.opacity;

Set the opacity property:

object.style.opacity='number|initial|inherit"

Property Values

Value Description
number Set the opacity from 0.0 which is transparent to 1.0 which is opaque
initial Set to default value.
inherit Inherits from parent element.




Technical Details

Default Value: 1
Return Value: A string representing the opacity-level
CSS Version CSS3

Example

The following code shows how to make a DIV element transparent.


<!DOCTYPE html>
<html>
<head>
<style> 
#myDIV {<!--from   ww w .  j a  v  a2  s  .c  o  m-->
    position: absolute;
    width: 300px;
    height: 150px;
    background-color: red;
    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">
  test
</div>
<div id="myDIV">
</div>
<script>
function myFunction() {
    document.getElementById("myDIV").style.opacity = "0.5";
}
</script>
</body>
</html>

The code above is rendered as follows: