Selenium · Browser automation foundations

What are Selenium relative locators and when should you use them?

Mediumrelative locatorslocatorsselenium 4Updated Oct 2026
Quiz this track

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.

java
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));
The anchor should be stable; the target is then located by geometry.
  • 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.

Relative locators are not a substitute for fixing the DOM. A data-testid on the target is still more stable and easier to debug.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1How does near differ from below?
  2. 2What makes a good anchor element?
  3. 3Why can responsive layouts break relative locators?
  4. 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.