Back to All Scenarios
Scenario 50 of 100
Scroll & Page
Beginner
Scrolling Until an Element is Fully Visible
π―Scenario Overview
Scrolling Until an Element is Fully Visible
Key Takeaways & Cheat Sheet
- βLocate target element in the HTML DOM first
- βExecute JS scrollIntoView(true) to slide target into viewport
- βCombine scrolling actions with standard explicit visibility waits
- βEnsure sticky headers do not overlap target after scrolling
Short Direct Answer
To scroll until an element is fully visible, use the `scrollIntoView()` JavaScript command. For modern websites with sticky headers, scroll the element to the center of the viewport rather than the top to prevent it from getting covered.
β οΈ Senior Warning (Red Flag)
Do not assume scrollIntoView() completely solves click blocks. If your page has a sticky header, the element will scroll to the top and get covered by the header. Use block: "center" to prevent this.
π‘ STAR Deep Dive Explanation & Pro Tip
Using block: "center" ensures that the target element is positioned in the middle of the screen, keeping it clear of sticky headers and footer overlaps.
SeleniumAutomation.java
Selenium 4 + Java// β
Locate target element
WebElement element = driver.findElement(By.id("privacy-agreement-checkbox"));
// β
Best Practice: Scroll element to the center of the viewport
((JavascriptExecutor) driver).executeScript(
"arguments[0].scrollIntoView({block: 'center', inline: 'nearest'});",
element
);