PRACTICAL GUIDE / Selenium relative locators

Selenium Relative Locators: Geometry Rules and Layout Pitfalls

Use Selenium relative locators with clear geometry rules, stable anchors, responsive-layout checks, identity assertions, and actionable failure evidence.

By The Testing AcademyUpdated July 11, 20269 min read
All field guides
In this guide12 sections
  1. Understand the Rectangle Model
  2. Choose a Stable Anchor and Narrow Candidates
  3. Build and Verify a Relative Locator in Java
  4. Chain Conditions Sparingly
  5. Treat near as a Bounded Heuristic
  6. Control Responsive Layout Inputs
  7. Handle Hidden and Duplicate Layouts
  8. Collect Geometry as Failure Evidence
  9. Analyze Common Failure Modes
  10. Weigh Relative Locators Against Alternatives
  11. Operational Checklist
  12. Conclusion: Make Geometry Prove Its Match

What you will learn

  • Understand the Rectangle Model
  • Choose a Stable Anchor and Narrow Candidates
  • Build and Verify a Relative Locator in Java
  • Chain Conditions Sparingly

Selenium relative locators are spatial queries over the rendered page. They are strongest when a control has weak markup identity but sits in an intentional relationship to a stable anchor, such as the action button below a named pricing panel. They are fragile when a test treats visual proximity as permanent while responsive CSS, animation, or duplicated layouts can change the geometry.

Use them as a constrained locator strategy, not as a substitute for product semantics. Start with a narrow candidate type, choose an anchor the user can identify, apply the minimum spatial filters, and assert the selected element's accessible or business identity before acting.

Understand the Rectangle Model

The official Selenium locator guide explains that relative locators use getBoundingClientRect() to determine element size and position. Selenium first identifies candidates from the base locator, obtains geometry for candidates and anchors, applies conditions such as above, below, toLeftOf, toRightOf, or near, and returns matching elements.

This is not DOM traversal. A button nested in an unrelated container can still be geometrically below an anchor. CSS grid reordering can make source order disagree with screen order. Transforms, sticky positioning, collapsed regions, and breakpoint-specific duplicates affect the rectangles that the algorithm observes.

Animated field map

Relative Locator Geometry Flow

A stable anchor and a narrow candidate set are converted to rectangles, filtered spatially, and then verified by target identity.

  1. 01 / anchor locator

    Anchor Locator

    Resolve a unique element whose identity and layout role are stable.

  2. 02 / candidate elements

    Candidate Elements

    Start from a narrow tag, role-bearing selector, class, or test contract.

  3. 03 / client rectangles

    Client Rectangles

    Measure rendered position and dimensions in the active layout.

  4. 04 / spatial filter

    Spatial Filter

    Apply above, below, left, right, near, or a deliberate chain.

  5. 05 / stable match

    Verified Match

    Require one displayed candidate and assert its accessible identity.

Choose a Stable Anchor and Narrow Candidates

The anchor should be easier to identify than the target. A unique plan heading, form label, or named panel is better than a decorative icon whose position can shift. Prefer a By anchor when the component may rerender; Selenium can locate it at evaluation time. Use a previously found WebElement only when selecting that exact instance matters and the DOM is stable enough to avoid staleness.

The base locator controls the candidate population. with(By.tagName("button")) is acceptable inside a small component but broad at document scope. A class that means "plan action" or a component-scoped CSS selector reduces accidental matches before geometry is considered. Do not begin with every element and expect near to recover product meaning.

When multiple anchors match, each can expand the acceptable region. Assert anchor uniqueness separately, especially when desktop and mobile variants coexist in the DOM with one hidden by CSS.

Build and Verify a Relative Locator in Java

This example locates a button below the Pro plan heading, waits until exactly one displayed candidate remains, and verifies the accessible name before clicking. The identity assertion is essential: geometry finds a neighbor, while the assertion proves it is the intended action.

Java
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.time.Duration;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.locators.RelativeLocator;
import org.openqa.selenium.support.ui.WebDriverWait;

public final class PricingPage {
  private final WebDriver driver;

  public PricingPage(WebDriver driver) {
    this.driver = driver;
  }

  public void chooseProPlan() {
    By proHeading = By.cssSelector("[data-testid='plan-pro'] h2");
    By planAction = RelativeLocator.with(
            By.cssSelector("[data-testid^='plan-'] button"))
        .below(proHeading);

    WebElement button = new WebDriverWait(driver, Duration.ofSeconds(5))
        .until(current -> {
          List<WebElement> displayed = current.findElements(planAction).stream()
              .filter(WebElement::isDisplayed)
              .toList();
          return displayed.size() == 1 ? displayed.get(0) : null;
        });

    assertEquals("Choose Pro", button.getAccessibleName());
    button.click();
  }
}

If the page supplies a unique data-testid for the button itself, use it directly. The relative version earns its complexity only when the spatial relationship is part of the UI contract and target identity is otherwise inadequate.

Chain Conditions Sparingly

Chaining can disambiguate a regular arrangement: a button below an email field and to the right of a Cancel button. Each condition narrows the geometric intersection. Two clear constraints can be expressive; a long chain becomes an undocumented coordinate puzzle.

Java
By submit = RelativeLocator.with(By.tagName("button"))
    .below(By.id("email"))
    .toRightOf(By.id("cancel"));

WebElement submitButton = driver.findElement(submit);
assertEquals("Submit", submitButton.getAccessibleName());

Do not assume a chain selects the closest result unless the API contract says so. Query all matches when uniqueness matters and fail with the candidate list. If the desired condition is strict horizontal or vertical alignment, current Java APIs also expose straight-direction variants; use them only when alignment is an intentional design contract, not an incidental screenshot detail.

Treat near as a Bounded Heuristic

near is useful for compact forms and icon-label arrangements, and Java provides overloads that accept an explicit maximum distance in pixels. Supplying the distance makes the tolerance visible in code, but it does not turn proximity into semantic association. Font loading, validation messages, browser zoom, and localization can move elements enough to alter results.

Use near after narrowing the candidate type and assert target identity. Avoid a large distance chosen merely to make a flaky test pass. A wide radius can include controls from adjacent cards or rows and make the first returned element layout-dependent.

For a responsive product, test the relationship at named viewport profiles. Do not share one pixel tolerance across desktop, tablet, and mobile without evidence that the component preserves the same geometry.

Control Responsive Layout Inputs

Viewport dimensions, device scale, zoom, font availability, scrollbar presence, and localized copy can all affect layout. Establish a deterministic window size before navigation or session startup, install the expected fonts in CI, and wait for the component's ready state before evaluating rectangles. A document-ready event alone does not prove web fonts or asynchronous card content have settled.

Animations deserve a product-aware strategy. Prefer an application signal such as an expanded panel state or a stable class over sleeping for the animation duration. If the product supports reduced motion, the test profile can request it through an approved browser or application mechanism, but that profile must remain representative of the behavior being asserted.

Breakpoint changes can alter the logical design. A button that is right of an anchor on desktop may be below it on mobile. Model those as separate locator strategies or, better, ask the product to expose a stable semantic locator shared by both variants.

Handle Hidden and Duplicate Layouts

Responsive implementations sometimes render desktop and mobile controls simultaneously and hide one tree. Geometry for hidden elements can be zero-sized or otherwise unsuitable, while a visually hidden pattern may still occupy layout. Filter by displayed state, require one match, and inspect the product's accessibility tree when duplicate controls are present.

Relative locators do not remove browsing-context boundaries. Switch into the correct iframe before locating anchors and candidates. For open shadow DOM, enter the appropriate shadow root search context and prefer locators local to that component. Trying to use an anchor in one context to locate a target in another creates an unclear and brittle test design.

Virtualized lists are another poor fit. Off-screen records may not exist in the DOM, and scrolling can recycle elements and shift every rectangle. Locate the record by stable data identity, scroll it into view through the component's supported behavior, then use geometry only within the rendered record if necessary.

Collect Geometry as Failure Evidence

A screenshot shows the final layout but not the values the locator compared. On failure, capture the anchor and candidate rectangles, displayed state, text, accessible name, viewport size, URL, and active responsive profile. JavaScript can return a compact rectangle record for a known element.

Java
import java.util.Map;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;

@SuppressWarnings("unchecked")
static Map<String, Number> rectangle(WebDriver driver, WebElement element) {
  return (Map<String, Number>) ((JavascriptExecutor) driver).executeScript(
      "const r = arguments[0].getBoundingClientRect(); " +
      "return {x:r.x,y:r.y,width:r.width,height:r.height};",
      element);
}

If a WebElement becomes stale while collecting evidence, record that as a rerender signal and relocate from By. Do not swallow staleness and return an empty candidate list; those failure modes imply different fixes.

Analyze Common Failure Modes

The wrong element with a valid rectangle usually means the candidate selector was too broad or the business identity was never asserted. No match at one viewport suggests the spatial relationship changed. Intermittent multiple matches point to animation, duplicated layouts, or an anchor that is not unique. Stale anchors indicate a component rerender between discovery and filtering.

Cross-browser differences should first be checked against viewport, fonts, zoom, and scrollbar configuration. If those inputs are controlled and geometry still differs, decide whether the product layout contract allows that difference. Do not add browser-specific pixel offsets until the expected design behavior is explicit.

Weigh Relative Locators Against Alternatives

A stable ID, accessible name, label relationship, or deliberate test ID usually communicates intent better and survives layout changes. CSS is efficient for component structure, while XPath can express document relationships when that structure is itself stable. Relative locators are valuable when spatial arrangement is meaningful and markup cannot uniquely identify the target.

Their tradeoff is observability and sensitivity. They read naturally but depend on rendered geometry, so failures need richer evidence and more controlled environment inputs. Use them at the page-component boundary, wrap them in domain-named methods, and keep direct semantic alternatives available when the product evolves.

Operational Checklist

  • Confirm that geometry is part of the intended UI relationship.
  • Use a unique, user-recognizable anchor.
  • Narrow the base candidate locator before applying spatial rules.
  • Prefer a By anchor when the component can rerender.
  • Apply no more spatial conditions than needed.
  • Require exactly one displayed result.
  • Assert accessible name or business identity before interaction.
  • Define viewport, fonts, locale, zoom, and motion inputs.
  • Keep iframe and shadow-root searches within one context.
  • Capture rectangles and candidate details on failure.

Conclusion: Make Geometry Prove Its Match

Relative locators are dependable when the layout relationship is intentional, the environment is controlled, and the selected element must still prove who it is. Anchor the query in product meaning, constrain the candidate set, inspect all matches, and treat responsive changes as separate contracts. When a direct semantic locator becomes available, take it; geometry should solve the hard cases, not become the default language of the suite.

// LIVE COURSE / THE TESTING ACADEMY

Playwright Automation Mastery

Go beyond Selenium. Master Playwright with JS/TS in 90 days.

From the instructor behind this guide.

Playwright jobs are growing 8x faster than Selenium. 90 days / 75+ live hrs / Tue-Thu-Sat 7 AM IST.

Code PROMODE / 10% offJoin the batch

The Testing Academy editorial desk

Practical QA guidance built around test evidence, production tradeoffs, and interview-ready explanations.

Published July 11, 2026 / Reviewed July 11, 2026

PRIMARY REFERENCES

Verify the details at the source

QABattle guides are practical explanations. Product behavior, standards, and APIs can change, so use these primary references for the canonical details.

  1. 01
    Selenium documentation

    Selenium Project

    Canonical WebDriver, Grid, waits, element, and browser automation guidance.

  2. 02
    WebDriver standard

    W3C

    The browser automation protocol specification behind WebDriver implementations.

FAQ / QUICK ANSWERS

Questions testers ask

How do Selenium relative locators determine above and below?

Selenium evaluates element rectangles from the rendered page and applies spatial filters relative to an anchor. It is geometry-based, not DOM sibling order or visual text association.

Are relative locators reliable on responsive layouts?

Only when the tested viewport preserves the spatial relationship. A breakpoint can stack, reorder, hide, or duplicate controls, so define viewport contracts and verify target identity.

Should a relative locator use a WebElement or a By anchor?

A By anchor is usually easier to re-evaluate after DOM changes. A WebElement anchor is useful when the exact instance was already selected, but it can become stale after a rerender.

Can relative locators replace IDs and accessible selectors?

No. Prefer a unique semantic or test contract when one exists. Relative locators are valuable when the target lacks identity but a stable nearby anchor and layout relationship are intentional.

How should a test debug the wrong relative-locator match?

Capture every candidate's text, accessible name, displayed state, and rectangle together with the anchor rectangle, viewport size, screenshot, and active breakpoint.