Selenium · Browser automation foundations

How do CSS selectors work in Selenium and where do they break?

Mediumcss selectorslocatorsdomUpdated Oct 2026
Quiz this track

Short answer

CSS selectors match elements by tag, id, class, attribute and structural relationships. They are fast and readable, but positional and generated-class selectors become brittle when the DOM changes.

CSS selectors are evaluated by the browser and generally perform well. They express attributes and simple relationships clearly. The weaknesses are text matching and parent or sibling traversal, which are easier in XPath.

java
By byId = By.cssSelector("#email");
By byClass = By.cssSelector(".form-control");
By byAttribute = By.cssSelector("input[type='email']");
By byTestId = By.cssSelector("[data-testid='sign-in']");
By byDescendant = By.cssSelector("form.login input[name='password']");
By byDirectChild = By.cssSelector("ul.menu > li.active");
By byMultiple = By.cssSelector("button.primary, button.secondary");
Attribute selectors are the most stable option when the attribute is meaningful.
  • #id selects an id, .class selects a class, and tag selects an element type
  • [attr='value'] selects by attribute equality
  • A space means descendant; > means direct child
  • :nth-child and :nth-of-type are positional and often brittle
  • :not() and attribute prefixes such as ^= and *= can help with dynamic ids
  • CSS cannot select a parent or match text content directly

A selector such as div:nth-child(3) > span encodes layout. It passes today and fails after a harmless wrapper is added. Prefer an attribute that describes the element's role or purpose, and keep selectors short enough that a failure points to one component.

If a selector needs five levels of ancestry, it is probably testing structure rather than behaviour. Ask whether the test should target a stable test id instead.

Follow-ups you should expect

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

  1. 1When can CSS not replace XPath?
  2. 2Why are nth-child selectors risky?
  3. 3How would you handle a dynamic id?
  4. 4Does CSS selector performance matter in practice?

Say it in the interview

I use CSS for attribute and simple relationship matching because it is fast and readable. I anchor on stable attributes such as data-testid or a meaningful name, and I avoid nth-child and long ancestor chains. CSS cannot match text or walk to a parent, so XPath is the fallback for those cases. If a selector starts encoding layout, I push for a test id instead.

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.