Quick interview answer
RelativeLocator (with, above, below, toLeftOf, toRightOf, near) finds an element by its visual position relative to a known one — useful for label-value pairs and grid cells with no stable attributes.
Detailed explanation
Relative locators work off the rendered bounding boxes returned by getBoundingClientRect, not the DOM tree, so they can cross unrelated branches of the markup. They are convenient for legacy tables where the only anchor is a label, but they are layout-dependent: a responsive breakpoint or a re-ordered column silently changes what 'toRightOf' means. Treat them as a fallback after data-test attributes and CSS, and never build a whole page object on them.
1import static org.openqa.selenium.support.locators.RelativeLocator.with;2 3WebElement emailLabel = driver.findElement(By.xpath("//label[text()='Email']"));4WebElement emailInput = driver.findElement(with(By.tagName("input")).toRightOf(emailLabel));5emailInput.sendKeys("qa@example.com");6 7WebElement totalCell = driver.findElement(8 with(By.tagName("td")).below(By.cssSelector("th#total")));Real-world example
An old ERP screen rendered inputs with generated ids that changed every deploy; anchoring on the visible label kept the tests stable.
Interview tip
Mention the layout fragility yourself — interviewers are testing whether you know the trade-off, not the syntax.
