Selenium · Browser automation foundations
What are Selenium relative locators and when should you use them?
Short answer
Relative locators find an element by its position relative to another element, using above, below, toLeftOf, toRightOf and near. They help when the target has no stable attribute, but they depend on layout.
RelativeLocator was added in Selenium 4. It builds a search from a known anchor element and a direction. The browser computes positions from rendered geometry, so the result depends on the current viewport and layout.
import static org.openqa.selenium.support.locators.RelativeLocator.with;
WebElement email = driver.findElement(By.id("email"));
WebElement password = driver.findElement(with(By.tagName("input")).below(email));
WebElement remember = driver.findElement(
with(By.tagName("input")).toRightOf(By.cssSelector("label[for='remember']")));
WebElement help = driver.findElement(with(By.tagName("a")).near(email));- above, below, toLeftOf and toRightOf express a direction
- near expands the search radius around the anchor
- Chained conditions such as below and toRightOf narrow the match
- The anchor element must be stable and visible for geometry to make sense
- Results can change with responsive layout, zoom and scrolling
Use relative locators as a pragmatic fallback for form fields or labels that lack test ids. Do not build core navigation on them. If a layout change moves the field, the locator breaks even though the feature still works.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1How does near differ from below?
- 2What makes a good anchor element?
- 3Why can responsive layouts break relative locators?
- 4Would you use relative locators for a primary checkout flow?
Say it in the interview
Relative locators let me find an element by direction from a stable anchor, using above, below, left, right or near. They are useful for labels and form fields without test ids. The catch is that they depend on rendered geometry, so responsive layout or zoom can change the result. I treat them as a fallback and still push for stable attributes on critical flows.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Selenium mock interview and get scored feedback on depth, clarity and confidence.