liveBook · Manning

Computed style

As explained in Secrets of the JavaScript Ninja, Second Edition

The set of CSS property values resolved for an element after the browser accounts for applicable browser defaults, style sheets, inline declarations, inheritance, and script changes.

An element’s computed style is the set of styles the browser resolves to apply after combining browser defaults, style sheets, the element’s style attribute, script changes, and inherited styles. section 12.3 section 12.3.3

Use `getComputedStyle(element)` to access the resolved styles, then call `getPropertyValue` with a CSS property name such as `background-color`.

  • Unlike properties on an element’s `style` object, `getPropertyValue` takes dashed CSS names. A helper can convert camel-cased names such as `backgroundColor` to dashed form before querying. section 12.3.3

Querying a resolved value

An element can get its background color from a style sheet and its text color from an inline style. Querying computed style retrieves the resolved value for either property. section 12.3.3

Figure 12.2. The final style associated with an element can come from many things: the browser builtin styles (user agent style sheet), the styles assigned through the style property, and styles from the CSS rules defined in CSS code.

The figure maps the different sources that contribute to an element’s final style. section 12.3.3

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Defines the contributing style sources and demonstrates property retrieval and name conversion without detailing browser internals.
Examples
Uses an element styled by both a style sheet and inline markup to demonstrate querying computed properties.
What you can do after
Apply `getComputedStyle` and `getPropertyValue` to retrieve an element’s resolved CSS values.
How it connects
Connects computed style to CSS style sheets, inline styles, inheritance, browser defaults, and the DOM style property.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.