The Window.getComputedStyle()
method returns an object containing the values of all CSS properties of an element, after applying active stylesheets and resolving any basic computation those values may contain.
Individual CSS property values are accessed through APIs provided by the object, or by indexing with CSS property names.
getComputedStyle(element)
getComputedStyle(element, pseudoElt)
A live CSSStyleDeclaration
object, which updates automatically when the element's styles are changed.
In this example we style a <p>
element, then retrieve those styles using getComputedStyle()
, and print them into the text content of the <p>
.
p {
width: 400px;
margin: 0 auto;
padding: 20px;
font: 2rem/2 sans-serif;
text-align: center;
background: purple;
color: white;
}
let para = document.querySelector('p');
let compStyles = window.getComputedStyle(para);
para.textContent = 'My computed font-size is ' +
compStyles.getPropertyValue('font-size') +
',\nand my computed line-height is ' +
compStyles.getPropertyValue('line-height') +
'.';
The returned object is the same CSSStyleDeclaration
type as the object returned from the element's style
property. However, the two objects have different purposes:
- The object from
getComputedStyle
is read-only, and should be used to inspect the element's style — including those set by a <style>
element or an external stylesheet.
- The
element.style
object should be used to set styles on that element, or inspect styles directly added to it from JavaScript manipulation or the global style
attribute.
The first argument must be an Element
. non-elements, like a Text
node, will throw an error.
In many code samples, getComputedStyle
is used from the document.defaultView
object. In nearly all cases, this is needless, as getComputedStyle
exists on the window
object as well. It's likely the defaultView
pattern was a combination of folks not wanting to write a testing spec for window
and making an API that was also usable in Java.
getComputedStyle
can pull style info from pseudo-elements (such as ::after
, ::before
, ::marker
, ::line-marker
— see the pseudo-element spec).
<style>
h3::after {
content: ' rocks!';
}
</style>
<h3>Generated content</h3>
<script>
var h3 = document.querySelector('h3');
var result = getComputedStyle(h3, ':after').content;
console.log('the generated content is: ', result);
</script>