Example 6: getComputedStyle
This example demonstrates how the DOM document.defaultView.getComputedStyle() method can be used to get the styles on an element that aren't set in-line or with JavaScript (e.g., element.style.backgroundColor="lightblue"). These latter types of styles can be retrieved with the more direct style = element.style property, a list of which properties is listed in the DOM Style Reference of this book (see DOM CSS Properties List). See also the style property in the DOM Elements Reference.
getComputedStyle() returns a ComputedCSSStyleDeclaration object, whose individual style properties can be referenced with this object's getPropertyValue() method, as the following example document shows.
<title>getComputedStyle</title>
div = document.getElementById("d1");
t1 = document.getElementById("t1");
h_style = document.defaultView.getComputedStyle(div, '').getPropertyValue("height");
t1.setAttribute("value", h_style);
t2 = document.getElementById("t2");
w_style = document.defaultView.getComputedStyle(div, '').getPropertyValue("width");
t2.setAttribute("value", w_style);
t3 = document.getElementById("t3");
b_style = document.defaultView.getComputedStyle(div, '').getPropertyValue("background-color");
t3.setAttribute("value", b_style);
.d { margin-left: 10px; background-color: lightblue; height: 20px; max-width: 20px; }
<div id="d1" class="d"> </div>
<button onclick="cStyles();">getComputedStyle</button>
height<input id="t1" type="text" value="1" />
max-width<input id="t2" type="text" value="2" />
bg-color<input id="t3" type="text" value="3" /></pre>