How Relative Locators Decide

Rectangles on the Page

Relative locators use each element's bounding box (x, y, width, height) and sort the matches by distance. This runnable model, with boxes as Selenium would read them via getRect(), picks the input to the right of the "Email" label:

Example

Simulated layout of the login form:

import java.util.*;

public class Main {
    record Box(String name, int x, int y, int w, int h) {
        int right() { return x + w; }
        int centerY() { return y + h / 2; }
    }

    static List<Box> toRightOf(List<Box> candidates, Box anchor) {
        List<Box> hits = new ArrayList<>();
        for (Box b : candidates) if (b.x() >= anchor.right()) hits.add(b);
        hits.sort(Comparator.comparingDouble(b ->
                Math.hypot(b.x() - anchor.right(), b.centerY() - anchor.centerY())));   // nearest first
        return hits;
    }

    public static void main(String[] args) {
        Box emailLabel = new Box("label Email", 20, 100, 80, 20);
        List<Box> inputs = List.of(
            new Box("input#f1 (email)", 120, 98, 200, 24),
            new Box("input#f2 (password)", 120, 140, 200, 24),
            new Box("input#q (search)", 400, 10, 300, 30));

        List<Box> result = toRightOf(inputs, emailLabel);
        for (Box b : result) System.out.println("candidate: " + b.name());
        System.out.println("findElement returns: " + result.get(0).name());
    }
}

Output

candidate: input#f1 (email)
candidate: input#f2 (password)
candidate: input#q (search)
findElement returns: input#f1 (email)