How do I use `getCssValue()` in Selenium WebDriver?

I’m trying to retrieve CSS property values from a web element using getCssValue(). For example, I want the font size of the section with id="by-id".

I also noticed that driver.close() didn’t close the browser after my script finished. Why is that? How should I properly close the browser?

Example code:

WebDriver driver = new FirefoxDriver();
driver.get("http://docs.seleniumhq.org/docs/03_webdriver.jsp#introducing-the-selenium-webdriver-api-by-example");

List<WebElement> elements = driver.findElements(By.id("by-id"));
for(WebElement ele : elements){
    System.out.println(ele.getTagName());
    System.out.println(ele.getText());
    System.out.println(ele.getAttribute("id"));
    System.out.println(ele.getCssValue("font-size"));
}

driver.quit(); // recommended over driver.close() here

Hey! getCssValue() retrieves the computed value of a CSS property for a WebElement. For example, if you want the font size of an element:

WebElement element = driver.findElement(By.id("by-id"));
String fontSize = element.getCssValue("font-size");
System.out.println("Font size: " + fontSize);

It works for any CSS property, like color, background-color, margin, etc. Just make sure you pass the property as it appears in CSS (background-color, font-size) rather than Java-style (backgroundColor).

If you use driver.close(), it only closes the current window. If your WebDriver session has multiple tabs/windows, the browser process may stay alive. For cleanup, always use:

driver.quit();

quit() ends the session and closes all associated windows, freeing resources. This is why most Selenium examples recommend quit() instead of close() at the end.

When dealing with multiple elements:

List<WebElement> elements = driver.findElements(By.cssSelector(".some-class"));

for (WebElement ele : elements) {
    System.out.println("Tag: " + ele.getTagName());
    System.out.println("Text: " + ele.getText());
    System.out.println("ID: " + ele.getAttribute("id"));
    System.out.println("Font-size: " + ele.getCssValue("font-size"));
}

This way, you can inspect styling across multiple elements. Remember, getCssValue() returns the computed style, which may differ slightly from what you see in your stylesheet if the browser applies defaults or inherited styles.