In my UI tests I would like to verify particular style values for the elements. Below is the example list of the styles I'd like to verify:

  • font style
  • font size
  • padding
  • margin

Is there a way to do that using Selenium?

  • 2
    Your question is too broad, make it more specific. Ask seperate questions. Give more context and explain what you tried already. Read how to ask questions: sqa.stackexchange.com/help/how-to-ask Aug 13 '18 at 12:43
  • @NielsvanReijmersdal why too broad? Isn't the question specific: How to test style attributes with Selenium?
    – beatngu13
    Sep 19 '18 at 13:35
  • The edited question is better, it removed images, the original question also used to the word "like" a couple of times. Sep 19 '18 at 19:37

Selenium does not let you pick the current style of an element unless it is specified in style attribute of that element. However you can use JavaScript to pick any evaluated style of the element and pass it to your Selenium script.

Below is the example for Java:

    WebElement el = driver.findElement(By.xpath("//a[text()='LEARN HTML']"));
    String contents = (String) ((JavascriptExecutor) driver)
            .executeScript("return window.getComputedStyle(arguments[0]).getPropertyValue('background-color');", el);

There’s recheck-web (disclaimer: I work for retest, the company behind the open-source project). recheck replaces asserts and checks everything at once, including CSS attributes. It operates on top of Selenium and currently offers a Java API:

public void index() throws Exception {
    // Set the file name of the Golden Master.
    re.startTest( "my-file-name" );

    // Do your Selenium stuff.
    driver.get( "https://my-url.org/" );

    // Single call instead of multiple assertions (doesn't fail on differences).
    re.check( driver, "my-step-name" );

    // Conclude the test case (fails on differences).

The library essentially follows the principles of Golden Master Testing and Whitelist Testing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.