THE WORLD'S LARGEST WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JavaScript Window getComputedStyle() Method

Window Object Reference Window Object

Example

Get the computed (actual showing) background color of a div:

<div id="test" style="height: 50px;background-color: lightblue;">Test Div</div>
<p>The computed background color for the test div is: <span id="demo"></span></p>

<script>
function myFunction() {
    var elem = document.getElementById("test");
    var theCSSprop = window.getComputedStyle(elem, null).getPropertyValue("background-color");
    document.getElementById("demo").innerHTML = theCSSprop;
}
</script>

The result will be:

The computed background color for the test div is: rgb(173, 216, 230)
Try it yourself »

More "Try it Yourself" examples below.


Definition and Usage

The getComputedStyle() method gets all the actual (computed) CSS property and values of the specified element.

The computed style is the style acutally used in displaying the element, after stylings from multiple sources have been apllied.

Style sources can include: internal style sheets, external style sheets, inherited styles and browser default styles.

The getComputedStyle() method returns a CSSStyleDeclaration object.


Browser Support

The numbers in the table specify the first browser version that fully supports the method.

Method
getComputedStyle() 11.0 12.0 9.0 4.0 5 11.5

Syntax

window.getComputedStyle(element, pseudoElement)

Parameter Values

Parameter Description
element Required. The element to get the computed style for
pseudoElement Optional. A pseudo-element to get

Technical Details

Return Value: A CSSStyleDeclaration object containing CSS declaration block of the element.

Examples

More Examples

Example

Get all the computed styles from an element:

<div id="test" style="height: 50px;background-color: lightblue;">Test Div</div>
<p>The computed styles for the test div are: <br><span id="demo"></span></p>

<script>
function myFunction(){
    var elem = document.getElementById("test");
    var txt;
    cssObj = window.getComputedStyle(elem, null)

    for (i = 0; i < cssObj.length; i++) {
        cssObjProp = cssObj.item(i)
        txt += cssObjProp + " = " + cssObj.getPropertyValue(cssObjProp) + "<br>";
    }
    document.getElementById("demo").innerHTML = txt;
}
</script>
Try it yourself »

Example

Get computer font size of the first letter in the test div (using pseudo-element):

<div id="test" style="height: 50px;background-color: lightblue;">Test Div</div>
<p>The computed font size for div::first-letter in the test div is: <span id="demo"></span></p>

<script>
function myFunction(){
    var elem = document.getElementById("test");
    var theCSSprop = window.getComputedStyle(elem, "first-letter").getPropertyValue("font-size");
    document.getElementById("demo").innerHTML = theCSSprop;
}
</script>
Try it yourself »

Window Object Reference Window Object