Get CSS properties of web element with Playwright

Shiv Jirwankar
2 min readSep 17, 2023

--

We often come across the situation where we need to verify the CSS property of a web element. Following are some common use cases where we would require to validate CSS properties:

  1. Color of an element.
  2. Color of border of an element.
  3. Color of an element after some action has been performed.

Let’s discuss how we can get the CSS properties of a web element when developing tests with Playwright library.

Usage of Window.getComputedStyle()

We will be using Window.getComputedStyle() method. This method returns an object containing the values of all CSS properties of an element.

Syntax

getComputedStyle(element)
getComputedStyle(element, pseudoElt)

Parameters

element

The element for which to get the computed style.

pseudoElt Optional

A string specifying the pseudo-element to match. Omitted (or null) for real elements.

Return value

A live CSSStyleDeclaration object, which updates automatically when the element's styles are changed.

Implementation

We will use page.evaluate() function to execute JavaScript code in the context of the current page.

Let’s consider an instance where we need to get the background-color of ‘Accept’ button. Here’s how the implementation will look:

const element: Locator = await page.getByTestId('accept-button);
const backgroundColor = await element.evaluate((el) => {
return window.getComputedStyle(el).getPropertyValue('background-color');
});

backgroundColor variable will have either RGB or HSL format.

If the background-color property is specified in RGB format, the returned value will be in the format rgb(r, g, b), where r, g, and b are integers between 0 and 255 that represent the red, green, and blue components of the color.

If the background-color property is specified in HSL format, the returned value will be in the format hsl(h, s%, l%), where h is an integer between 0 and 360 that represents the hue of the color, s% is a percentage between 0% and 100% that represents the saturation of the color, and l% is a percentage between 0% and 100% that represents the lightness of the color.

Likewise, we can get any other CSS property which belongs to the element and do the required validation test.

Shiv Jirwankar

SDET

LinkedIn.

--

--