How to get the CSS computed style values of an HTML element

About

To get the computed values of a style for an HTML element, you use the browser webapi window.getComputedStyle.

Part of the calculation of values depends on the formatting algorithm appropriate for the target media type (display).

For example, if the target medium is the screen, user agents apply the visual formatting model.

Example

Get by name

Retrieving the display

<h1>Article Title</h1>
let title = document.querySelector('h1');
let display = window.getComputedStyle(title).getPropertyValue('display');
console.log('The display of the heading h1 is :'+display);

Get all by index

  • The HTML
<h1>Title</h1>
<p>Below in the log container, you can see all default computed style of the browser for the title.
let title = document.querySelector('h1');
let styles = window.getComputedStyle(title);
for(var i = 0; i < styles.length; i++){
    attributeName = styles.item(i);
    value = styles .getPropertyValue(attributeName);
    console.log(attributeName+" : "+value);
}

With Computed Style Map

  • The HTML
<h1 style="border: 1px solid blue; width: fit-content; padding: 1rem">Title</h1>
  • The Javascript that will lookup the border
let borderDeclaration = document
    .querySelector("h1")
    .computedStyleMap()
    .get('border')
    .toString()
console.log(`The border declaration is: ${borderDeclaration}`)
  • The result:





Discover More
Boxdim
CSS - Length Value (Size)

CSS Lengths refer to horizontal or vertical measurements. The format of a length value is a number (with or without a decimal point) immediately followed by a unit identifier where: number is...
CSS - Property

CSS defines a finite set of parameters, called properties, that defines the rendering of a document. Properties are written in a css rule after the element selection definition. Properties are attached...
Boxdim
CSS - Relative Sizing (Length)

Relative Sizing is when you are using a length units that is relative to another length property. Style sheets that use relative units will more easily scale from one medium to another (e.g., from a...
CSS - line-height Property

On block level elements, the line-height property specifies the space between the text lines and is known as the Leading where: the value is one of: normal, - let the browser choose a reasonable...
Css - Declaration

Declaration are syntactic expressions that are contained in a declaration block to create a rule A declaration: is either empty or has two parts (separated by a colon (:) and optionally surrounded...
DOM - Body

The body node in the DOM tree represents the HTML body element. You access the body node via the document node as property. Example: getComputedcomputed style value Document/body
How to get a list of CSS difference styles between two HTML elements with Javascript

This article shows you how to list the CSS style difference between two HTML elements.



Share this page:
Follow us:
Task Runner