HTML - DOM Style Object opacity Property



HTML DOM Style Object opacity property sets or returns opacity level or transparency level of an element where 0 represents completely transparent and 1 represents not transparent at all.

Syntax

Set the opacity property:
object.style.opacity= "number | initial | inherit";
Get the opacity property:
object.style.opacity;

Property Values

Value Description
number It specifies the opacity value from 0 to 1.
initial It is used to set this property to it's default value.
inherit It is used to inherit the property of it's parent element.

Return Value

It returns a string which represents opacity level of an element.

Examples of HTML DOM Style Object 'opacity' Property

The following examples sets the opacity level of a div element and an image.

Set Opacity for div Element

The following example sets the opacity level for a div element.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM Style Object opacity Property
    </title>
    <style>
        #opacity {
           height: 250px;
           width: 250px;
           background-color: #04af2f;
        }
    </style>
</head>
<body>
    <h3>
        Click to set opacity property.
    </h3>
    <button onclick="fun()">Set Opacity</button>
    <br>
    <div id="opacity">
    </div>
    <script>
        function fun() {
            let x = document.getElementById("opacity")
                .style.opacity = "0.3";
        }
    </script>
</body>
</html>

Set Opacity for an Image

The following example sets the opacity level for an image.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM Style Object opacity Property
    </title>
</head>
<body>
    <h3>
        Click to set opacity property.
    </h3>
    <button onclick="fun()">Set Opacity</button>
    <br>
    <img src="/html/images/test.png"id="opacity">
    <script>
        function fun() {
            let x = document.getElementById("opacity")
                .style.opacity = "0.3";
        }
    </script>
</body>
</html>

Supported Browsers

Property Chrome Edge Firefox Safari Opera
opacity Yes 1 Yes 12 Yes 1 Yes 2 Yes 9
html_dom.htm
Advertisements