Glossary · UI automation
CSS selector
Also called: CSS selectors, CSS locator, CSS locators
Definition
A pattern from the CSS language that matches elements by tag, id, class, attribute or position, widely used as a fast and readable UI test locator.
A CSS selector is the same pattern a stylesheet uses to decide which elements a rule applies to. Test tools reuse it to find elements: Selenium through By.cssSelector, Playwright through page.locator(), Cypress through cy.get(). Selectors are evaluated natively by the browser, are usually shorter than the equivalent XPath, and most front-end developers can read them.
Example
#email id
.alert.alert-error element with both classes
button[type="submit"] tag plus attribute
[data-testid="checkout"] dedicated test attribute
form.login > button direct child
ul.results li:nth-child(2) second list item
a[href^="/invoices/"] attribute starts with
input:not([disabled]) negation
driver.findElement(By.cssSelector("[data-testid='checkout']")).click();
await page.locator('[data-testid="checkout"]').click();
How it differs from XPath
- Text matching. Standard CSS cannot select by text content. XPath can, and Playwright adds its own text engines (
getByText, and the:has-text()pseudo-class insidepage.locator()), but those are Playwright extensions, not CSS. - Direction. For years CSS could only go downwards. The
:has()pseudo-class, now supported in current browsers, lets you match a parent by its children (tr:has(td.overdue)), which closes much of the gap. - Readability. For id, class and attribute matching, CSS is shorter and clearer.
Common mistakes
- Styling classes as locators.
.btn-bluechanges when the design changes. Utility-class frameworks make this worse. - Long structural chains.
div > div > div:nth-child(3) spanencodes the layout and breaks when a wrapper is added. - Confusing
:nth-childwith:nth-of-type.li:nth-child(2)means “anlithat is the second child of its parent”, not “the secondli”.
When you control the markup, a data-testid attribute agreed with developers is the most stable CSS locator. When you don’t, prefer role-based locators where the framework offers them.