Get Width and Height of Element

To get the width and height of a rendered web element programmatically using Selenium in Java, use WebElement.getSize() function.

We first find the web element by name, id, class name, etc., and then call the getSize() function on this web element. getSize() function returns a Dimension object.

The following is a simple code snippet where we find an element with the name q and then get the dimensions (width, height) programmatically.

</>
Copy
WebElement searchBox = driver.findElement(By.name("q"));
Dimension dim = searchBox.getSize();

Example

In the following program, we write Java code to find a web element with the name q, get its width and height after rendering, and print these values to console output.

Java Program

</>
Copy
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.time.Duration;

public class MyAppTest {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");  
    	WebDriver driver = new ChromeDriver();
        driver.get("https://google.com/ncr");
        driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));

        WebElement searchBox = driver.findElement(By.name("q"));
        Dimension dim = searchBox.getSize();
        
        System.out.println(dim);

        driver.quit();
    }
}

Output

(487, 34)

We may access the width and height using the Dimension.width and Dimension.height properties respectively.

Java Program

</>
Copy
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.time.Duration;

public class MyAppTest {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");  
    	WebDriver driver = new ChromeDriver();
        driver.get("https://google.com/ncr");
        driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));

        WebElement searchBox = driver.findElement(By.name("q"));
        Dimension dim = searchBox.getSize();
        
        System.out.println("Width : " + dim.width);
        System.out.println("Height : " + dim.height);

        driver.quit();
    }
}

Output

Width : 487
Height : 34