---
title: CSS Selectors for Test Automation | TestingBot
description: CSS selectors are the workhorse of web test automation. Every browser
  has a fast native engine for them, Selenium sends `By.ID`, `By.NAME` and…
source_url:
  html: https://testingbot.com/resources/courses/locator-strategies/css-selectors
  md: https://testingbot.com/resources/courses/locator-strategies/css-selectors.md
---

Course

[Selenium Locators and Locator Strategies](https://testingbot.com/resources/courses/locator-strategies)

Chapter 4 of 12

1. [1 Selenium Locators: Strategies That Survive Change](https://testingbot.com/resources/courses/locator-strategies)
2. [2 Why Tests Break on Locators](https://testingbot.com/resources/courses/locator-strategies/why-locators-break)
3. [3 Inspect the DOM and Test Selectors in DevTools](https://testingbot.com/resources/courses/locator-strategies/inspect-and-test-selectors-in-devtools)
4. [4 CSS Selectors for Test Automation](https://testingbot.com/resources/courses/locator-strategies/css-selectors)
5. [5 XPath in Selenium: Text, Axes and When to Use It](https://testingbot.com/resources/courses/locator-strategies/xpath-in-selenium)
6. [6 Role-Based, Label and Relative Locators](https://testingbot.com/resources/courses/locator-strategies/role-based-and-relative-locators)
7. [7 A Test ID Contract With Your Developers](https://testingbot.com/resources/courses/locator-strategies/a-test-id-contract)
8. [8 Shadow DOM and iframes](https://testingbot.com/resources/courses/locator-strategies/shadow-dom-and-iframes)
9. [9 Lists, Tables and Dynamic Content](https://testingbot.com/resources/courses/locator-strategies/lists-tables-and-dynamic-content)
10. [10 A Note on Mobile Locators](https://testingbot.com/resources/courses/locator-strategies/a-note-on-mobile-locators)
11. [11 A Locator Review Checklist](https://testingbot.com/resources/courses/locator-strategies/locator-review-checklist)
12. [12 Locator Strategies Knowledge Check](https://testingbot.com/resources/courses/locator-strategies/knowledge-check)

[Exit course](https://testingbot.com/resources/courses)

 Chapter 4 of 12 Intermediate 6 min read 2 quick checks Updated Nov 2026 

# CSS Selectors for Test Automation
On this page
1. [The building blocks](https://testingbot.com#the-building-blocks)
2. [Attribute selectors do most of the work](https://testingbot.com#attribute-selectors-do-most-of-the-work)
3. [Classes: use the ones that mean something](https://testingbot.com#classes-use-the-ones-that-mean-something)
4. [Combinators and position](https://testingbot.com#combinators-and-position)
5. [:has() selects a parent](https://testingbot.com#has-selects-a-parent)
6. [What CSS cannot do](https://testingbot.com#what-css-cannot-do)
7. [Summary](https://testingbot.com#summary)

CSS selectors are the workhorse of web test automation. Every browser has a fast native engine for them, Selenium sends `By.ID`, `By.NAME` and `By.CLASS_NAME` to the browser as CSS under the hood, and Playwright's `page.locator('...')` treats a plain string as CSS. This chapter covers the parts of CSS that matter for tests, and the parts that quietly make tests brittle.

## The building blocks[#](https://testingbot.com#the-building-blocks)

| Selector | Matches | Example |
| --- | --- | --- |
| `tag` | elements of that type | `button` |
| `#id` | the element with that id | `#username` |
| `.class` | elements with that class (one of possibly several) | `.email` |
| `[attr]` | elements that have the attribute | `[disabled]` |
| `[attr='v']` | attribute equals `v` | `[name='my-text']` |
| `[attr^='v']` | starts with | `[name^='my-d']` |
| `[attr$='v']` | ends with | `[href$='.pdf']` |
| `[attr*='v']` | contains | `[href*='invoice']` |
| `A B` | `B` anywhere inside `A` | `#table2 td.email` |
| `A > B` | `B` that is a direct child of `A` | `tr > td` |
| `A + B` / `A ~ B` | `B` right after / anywhere after sibling `A` | `label + input` |
| `:checked`, `:disabled`, `:not(...)` | state and negation | `input:not([disabled])` |
| `:nth-child(n)` | the n-th child of its parent | `tr:nth-child(2)` |
| `:has(...)` | elements that contain a match | `label:has(input:disabled)` |

Combine them without spaces to describe one element (`input.form-control[name='my-text']`), and with a space or `>` to describe a path.

## Attribute selectors do most of the work[#](https://testingbot.com#attribute-selectors-do-most-of-the-work)

The Selenium project's web form, `https://www.selenium.dev/selenium/web/web-form.html`, is a typical Bootstrap form: every input has the class `form-control` and a meaningful `name`. The class says how it looks; the `name` says what it is. Select on the `name` (`tests/test_css.py`):

```python
from selenium.webdriver.common.by import By

FORM = "https://www.selenium.dev/selenium/web/web-form.html"
TABLES = "https://the-internet.herokuapp.com/tables"

def css(driver, selector):
    return driver.find_elements(By.CSS_SELECTOR, selector)

def test_attribute_selectors(driver):
    driver.get(FORM)
    assert len(css(driver, "input[name='my-text']")) == 1
    assert len(css(driver, "[name^='my-d']")) == 3 # my-disabled, my-datalist, my-date
    assert len(css(driver, "input[type='checkbox']:checked")) == 1
    assert len(css(driver, "input.form-control:not([disabled]):not([readonly])")) == 6
```

Things to notice:

- **Quote attribute values.** `[name='my-text']` works for any value; the unquoted form breaks as soon as a value contains a space, a dot or starts with a digit.
- **Prefix and contains matches are blunt.** `[name^='my-d']` matched three fields here, which is fine for a count and dangerous for a click. Use them for families of elements whose names you control, such as `[data-testid^='invoice-row-']`.
- **State pseudo-classes** like `:checked` and `:disabled` read the live state of the element, not the original HTML attribute, so they reflect what the user has done.

## Classes: use the ones that mean something[#](https://testingbot.com#classes-use-the-ones-that-mean-something)

`By.CLASS_NAME` and `.class` are fine when the class names a _thing_ (`.email`, `.invoice-total`, `.todo-list`). They are brittle when the class names a _look_ (`.btn-primary`, `.mt-3`, `.col-md-4`) or is generated by a CSS-in-JS tool (`.css-1x2y3z`, `.sc-bdVaJa`). Those change with every redesign or build.

The tables page shows the difference. Table 1 has no classes at all; table 2 marks every cell with what it holds:

```html
<td class='last-name'>Smith</td>
<td class='first-name'>John</td>
<td class='email'>jsmith@gmail.com</td>
```

Semantic classes like these are nearly as good as test ids, and they are worth asking for.

Which selector for the "Place order" button is least likely to break when the design system is upgraded?

 `form#checkout button[type='submit']` `.btn.btn-lg.btn-primary` `.css-1q8x7v2` `div.col-md-4 > button`

A design-system upgrade changes visual classes, generated class names and grid wrappers. The form's id and the button's submit type describe what the element does, and neither depends on how it is styled.

## Combinators and position[#](https://testingbot.com#combinators-and-position)

Descend from a stable ancestor instead of starting from the top of the page:

```python
def test_combinators_and_position(driver):
    driver.get(TABLES)
    emails = css(driver, "#table2 tbody td.email")
    assert [e.text for e in emails][:2] == ["jsmith@gmail.com", "fbach@yahoo.com"]
    second = driver.find_element(By.CSS_SELECTOR, "#table2 tbody tr:nth-child(2) > td.email")
    assert second.text == "fbach@yahoo.com"
```

`#table2 tbody td.email` reads well: the email cells in table 2's body. The second selector works too, but `:nth-child(2)` is a bet that Frank Bach will always be the second row. Sort the table and the bet is lost. Positions are acceptable when the order _is_ the thing under test ("the newest message is first") and a smell everywhere else. Chapter 8 shows how to find a row by its content instead.

A detail that trips people up: `:nth-child(2)` means "the second child of its parent, if it also matches the rest of the selector", not "the second match". `tr:nth-child(2)` and `td.email:nth-child(2)` count different things. When you want "the second of these", count in code (`emails[1]`) or use Playwright's `.nth(1)`.

## `:has()` selects a parent[#](https://testingbot.com#has-selects-a-parent)

For years CSS could only go _down_ the tree, which was the main reason testers reached for XPath. The `:has()` pseudo-class, supported in current Chrome, Edge, Firefox and Safari, lets you select an element by what it contains:

```python
def test_has_selects_a_parent(driver):
    driver.get(FORM)
    label = css(driver, "label:has(input:disabled)")
    assert len(label) == 1
    assert label[0].text.startswith("Disabled input")
```

"The label that contains a disabled input" was XPath-only territory before. `tr:has(a[href='#edit'])` and `li:has(input:checked)` work the same way. Check `:has()` against the oldest browser in your matrix before relying on it: older browser versions you may still test on do not support it.

You need the table row that contains a checked checkbox. Which selector does that in CSS alone?

 `tr > input:checked` `input:checked < tr` `tr:has(input:checked)` It cannot be done without XPath

`:has()` selects the element that contains a match. Option a selects the input, not the row (and only if it is a direct child of the row, which it never is inside a cell). There is no `<` combinator in CSS.

## What CSS cannot do[#](https://testingbot.com#what-css-cannot-do)

CSS cannot match an element by its text content. There is no `button:contains('Save')` in the standard; jQuery and some old tools added it, and it fails in Selenium with an invalid selector error. When the text _is_ the best handle, use a role or label locator (chapter 5), Playwright's `:has-text()` extension, or XPath (next chapter).

## Summary[#](https://testingbot.com#summary)

- Select on attributes that say what an element is (`name`, `type`, semantic classes, test ids), not how it looks.
- Start from a stable ancestor and keep the path short.
- Treat `:nth-child()` as a statement that order matters; it usually does not.
- `:has()` covers most "parent of" cases that used to need XPath.
- CSS cannot match on text.

[Previous · Chapter 3 Inspect the DOM and Test Selectors in DevTools](https://testingbot.com/resources/courses/locator-strategies/inspect-and-test-selectors-in-devtools) [Next · Chapter 5 XPath in Selenium: Text, Axes and When to Use It](https://testingbot.com/resources/courses/locator-strategies/xpath-in-selenium)

On this page

1. [The building blocks](https://testingbot.com#the-building-blocks)
2. [Attribute selectors do most of the work](https://testingbot.com#attribute-selectors-do-most-of-the-work)
3. [Classes: use the ones that mean something](https://testingbot.com#classes-use-the-ones-that-mean-something)
4. [Combinators and position](https://testingbot.com#combinators-and-position)
5. [:has() selects a parent](https://testingbot.com#has-selects-a-parent)
6. [What CSS cannot do](https://testingbot.com#what-css-cannot-do)
7. [Summary](https://testingbot.com#summary)

Certification

Earn the free, resume-worthy TestingBot Locator Strategies Certification for this course.

[How it works](https://testingbot.com/resources/courses/locator-strategies/certification)
