Q20 of 37 · Selenium
How do you scroll to an element in the page?
Short answer
Short answer: Use `executeScript("arguments[0].scrollIntoView({block:'center'})", element)` — reliable across browsers. Actions.moveToElement also scrolls in Selenium 4. Avoid scrollIntoView(true) which slams the element to the very top and may collide with sticky headers.
Detail
Modern pages routinely lazy-load content as the user scrolls, so an element below the fold may not be clickable — or may not even exist — until you scroll to it. Selenium has a few ways to do that.
Option 1 — JavaScript scrollIntoView (most common):
WebElement el = driver.findElement(By.cssSelector("[data-test=row-99]"));
((JavascriptExecutor) driver).executeScript(
"arguments[0].scrollIntoView({block: 'center', inline: 'nearest'});", el
);
Use block: 'center' so the element ends up in the middle of the viewport — this avoids the trap where a sticky header overlaps the element after scrolling. scrollIntoView(true) (the no-arg / true form) puts the element flush with the top, which sticky navs commonly cover.
Option 2 — Selenium 4 Actions:
new Actions(driver).moveToElement(el).perform();
Selenium 4's Actions automatically scrolls if the element isn't in view. This is the cleanest approach for "click an off-screen button" but is slightly less precise about where the element ends up.
Option 3 — scroll by amount (for infinite scroll lists where the target doesn't yet exist):
((JavascriptExecutor) driver).executeScript("window.scrollBy(0, 800)");
Loop with a wait until the target appears, then scroll-into-view properly.
The frequent pitfall: scrolling, then clicking immediately, before the page settles. Add a short elementToBeClickable wait between scroll and click — the element may need a frame to finish rendering or animation.
// EXAMPLE
WebElement target = driver.findElement(By.cssSelector("[data-test=row-99]"));
((JavascriptExecutor) driver).executeScript(
"arguments[0].scrollIntoView({block: 'center'});", target
);
// Wait for the element to be ready after scroll-induced layout
new WebDriverWait(driver, Duration.ofSeconds(5))
.until(ExpectedConditions.elementToBeClickable(target));
target.click();