Selenium – CSS Selector for Identifying Web Elements

By Vijay

By Vijay

I'm Vijay, and I've been working on this blog for the past 20+ years! I’ve been in the IT industry for more than 20 years now. I completed my graduation in B.E. Computer Science from a reputed Pune university and then started my career in…

Learn about our editorial policies.
Updated May 9, 2025

In our previous Selenium tutorial, we learned different types of locators. We also learned how to use: ID, ClassName, Name, Link Text, and XPath locators for identifying web elements on a web page.

In continuation with that, today we will learn how to use CSS Selector as a Locator. This is the 6th tutorial in our free Selenium Training series.

Using CSS Selector as a Locator

CSS Selector Selenium Locator

CSS Selector is the combination of an element selector and a selector value that identifies the web element within a web page. The Selector Pattern refers to the combination of an element selector and a selector value.

The Selector Pattern is constructed using HTML tags, attributes, and their values. The central theme behind the procedure to create CSS Selector and Xpath are very much similar underlying the only difference in their construction protocol.

Like Xpath, CSS selectors can also locate web elements having no ID, class, or Name.

So now gearing ahead, let us discuss the primitive types of CSS Selectors:

Using CSS Selector as a Locator

CSS Selector: ID

In this sample, we would access the “Email” text box present in the login form at Gmail.com.

The Email text box has an ID attribute whose value is defined as “Email”. This ID attribute and its value can create a CSS Selector to access the email text box.

Creating CSS Selector for web element

Locate/inspect the web element (“Email” textbox in our case) and notice that the HTML tag is “input” and the value of the ID attribute is “Email” and both of them collectively refer to the “Email Textbox”. Hence, the above data would create a CSS Selector.

Using CSS Selector as a Locator 2

Verify the locator value

Type “css=input#Email” i.e. the locator value in the target box in the Selenium IDE and click on the Find button. Notice that the Email Text box will be highlighted.

Using CSS Selector as a Locator 3

Syntax:

css=<HTML tag><#><Value of ID attribute>

  • HTML tag – It is the tag that is used to denote the web element that we want to access.
  • # – The hash sign is used to symbolize the ID attribute. It is mandatory to use a hash sign if an ID attribute is being used to create a CSS Selector.
  • Value of ID attribute – It is the value of an ID attribute that is being accessed.
  • A hash sign always precedes the value of ID.

Note: Also applicable for other types of CSS Selectors

  • While specifying CSS Selector in the target text box of Selenium IDE, always remember to prefix it with “css=”.
  • The sequence of the above artifacts is inalterable.
  • If two or more web elements have the same HTML tag and attribute value, the first element marked in the page source will be identified.

CSS Selector: Class

In this sample, we would access the “Stay signed in” checkbox present below the login form at gmail.com.

The “Stay signed in” checkbox has a Class attribute whose value is defined as “remember”. Thus, the Class attribute and its value can create a CSS Selector to access the designated web element.

Locating an element using Class as a CSS Selector is very much similar to using ID. The lone difference lies in their syntax formation.

Recommended Reading => Explore all about Bulma Elements and Components

Creating a CSS Selector for web element

Locate/inspect the web element (“Stay signed in” checkbox in our case) and notice that the HTML tag is “label” and the value of the ID attribute is “remember” and both of them collectively refer to the “Stay signed in” checkbox.

Verify the locator value

Type “css=label.remember” i.e. the locator value in the target box in the Selenium IDE and click on the Find Button. Notice that the “Stay signed in” checkbox will be highlighted.

Using CSS Selector as a Locator 4

Syntax:

css=<HTML tag><.><Value of Class attribute>

  • ‘.’ – The dot sign is used to symbolize Class attribute. It is mandatory to use a dot sign if a Class attribute is being used to create a CSS Selector.
  • The value of Class is always preceded by a dot sign.

CSS Selector: Attribute

In this sample, we would access the “Sign in” button present below the login form at gmail.com.

The “Sign in” button has a type attribute whose value is defined as “submit”. Thus, type attribute and its value can create a CSS Selector to access the designated web element.

Creating a CSS Selector for web element

Locate/inspect the web element (“Sign in” button in our case) and notice that the HTML tag is “input”, the attribute is type, and the value of the type attribute is “submit” and all of them together refer to the “Sign in” button.

Verify the locator value

Type “css=input[type=’submit’]” i.e. the locator value in the target box in the Selenium IDE and click on the Find Button. Notice that the “Sign in” button would be highlighted.

Using CSS Selector as a Locator 5

Syntax:

css=<HTML tag><[attribute=Value of attribute]>

  • Attribute – It is the attribute we want to use to create a CSS Selector. It can value, type, name, etc. It is recommended to choose an attribute whose value uniquely identifies the web element.
  • Value of attribute – It is the value of an attribute that is being accessed.

CSS Selector: ID/Class and attribute

In this sample, we would access the “Password” text box present in the login form at gmail.com.

The “Password” text box has an ID attribute whose value is defined as “Passwd”, type attribute whose value is defined as “password”. Thus, ID attribute, type attribute, and their values can create the CSS Selector to access the designated web element.

Creating a CSS Selector for web element

Locate/inspect the web element (“Password” text box in our case) and notice that the HTML tag is “input”, attributes are ID and type and their corresponding values are ”Passwd” and “password” and all of them together refer to the “Password” textbox.

Verify the locator value

Type “css=input#Passwd[name=’Passwd’]” i.e. the locator value in the target box in the Selenium IDE and click on the Find Button. Notice that the “Password” text box will be highlighted.

Using CSS Selector as a Locator 5

Syntax:

css=<HTML tag><. Or #><value of Class or ID attribute><[attribute=Value of attribute]>

Two or more attributes can also be furnished in the syntax. For example, “css=input#Passwd[type=’password’][name=’Passwd’]”.

CSS Selector: Sub-string

CSS in Selenium allows matching a partial string and thus deriving a very interesting feature to create CSS Selectors using substrings. Based on the mechanism used to match the substring, three ways exist to create CSS Selectors.

Types of mechanisms

Symbolic significance is attributed to all the underlying mechanisms.

  • Match a prefix
  • Match a suffix
  • Match a substring

Let us discuss them in detail.

#1) Match a prefix

It is used to correspond to the string with the help of a matching prefix.

Syntax:

css=<HTML tag><[attribute^=prefix of the string]>                

  • ^ – Symbolic notation to match a string using a prefix.
  • Prefix – It is the string based on which the match operation is performed. The likely string is expected to start with the specified string.

For Example: Let us consider “Password textbox”, so the corresponding CSS Selector would be:

css=input#Passwd[name^=’Pass’]

#2) Match a suffix

It is used to correspond to the string with the help of a matching suffix.

Syntax:

css=<HTML tag><[attribute$=suffix of the string]>                

  • # – Symbolic notation to match a string using a suffix.
  • The suffix – It is the string based on which match operation is performed. The specified string is expected to be the ending of the likely string.

For Example, let’s again consider “Password textbox”, so the corresponding CSS Selector would be:

css=input#Passwd[name$=’wd’]

#3) Match a substring

It is used to correspond to the string with the help of a matching substring.

Syntax:

css=<HTML tag><[attribute*=sub string]>                

  • * – Symbolic notation to match a string using a sub-string.
  • Sub string – It is the string based on which the match operation is performed. The likely string is expected to have the specified string pattern.

For Example, let’s again consider “Password textbox”, so the corresponding CSS Selector would be:

css=input#Passwd[name$=’wd’]

CSS Selector: Inner text

The inner text helps us identify and create CSS Selector using a string pattern that the HTML Tag manifests on the web page.

Consider, “Need help?” hyperlink present below the login form at gmail.com.

The anchor tag representing the hyperlink has a text enclosed within. Thus, this text can create a CSS Selector to access the designated web element.

Syntax:

css=<HTML tag><:><contains><(text)>

  • : – The dot sign is used to symbolize the contains method
  • Contains – It is the value of a Class attribute that is being accessed.
  • Text – The text that is displayed anywhere on the web page, irrespective of its location.

This is one of the most frequently used strategies to locate web element because of its simplified syntax.

Conclusion

Since creating CSS Selector and Xpath requires a lot of efforts and practice, thus more sophisticated and trained users only exercised the process.

Next Tutorial #7: Proceeding ahead with our next tutorial, we will introduce you with an extension of locating strategies. In the upcoming tutorial, we’ll explore how to find web elements on Google Chrome and Internet Explorer.

We are covering Selenium Locators in more detail, as it is an important part of Selenium Script creation.

Let us know your queries/comments below.

Was this helpful?

Thanks for your feedback!

Recommended Reading

  • Locate Elements in Chrome and IE Browsers

    This is tutorial #7 in our Selenium Online Training Series. If you want to check all Selenium tutorials in this series, please check this page. In the previous tutorial, we tried to shed light on various types of locators in Selenium and their locating mechanisms to build test scripts. The…

  • Handling Web Tables, Frames, and Dynamic Elements in Selenium Script

    In the last Selenium WebDriver tutorial, we learned various commonly and routinely used Selenium WebDriver commands, including important topics like handling iframe and exceptions in Selenium scripts. Moving ahead in our comprehensive series of tutorials on Selenium, we will discuss handling Web tables, iframe, and dynamic elements which are an…

  • Working with Excel Objects in the VBScript

    Introduction to VBScript Excel Objects: Tutorial #11 In my previous tutorial, I explained ‘Events’ in the VBScript. In this tutorial, I will be discussing Excel Objects that are used in the VBScript. Please note that this is the 11th tutorial in our 'Learn VBScripting' series. VBScript supports different types of…

  • Automation Testing Using Cucumber Tool and Selenium

    In the last Selenium tutorial, we introduced you to Selenium Grid, which is a distributed test execution environment to speed up the execution of a test pass. Now at the end of this comprehensive Selenium training series, we are learning advanced Selenium testing and related concepts. In this and the…


READ MORE FROM THIS SERIES:



36 thoughts on “Selenium – CSS Selector for Identifying Web Elements”

  1. Thanks shruti,

    Is there anyway through which we can handle any kind of locator through a single statement or can some kind of mapping so that whenever i pass any locator it will automatically recognize whether it is an id /classname/xpath.

    Thanks

    Reply
  2. Creating CSS Selector for web element

    Step 1:

    There is correction.You have mentioned “notice that the html tag is “label” and value of ID attribute is “remember” ”

    Here its not Id attribute ,here we are taking about class attribute.Hence it should say ” value of class attribute is “remember” “

    Reply
  3. Hi,

    I have added a target with a value with CSS locator for site youtube.com but when i am trying to play whole test case suite it is throwing an error in logs.

    Target
    css=input#masthead-search-term
    Value
    Mache Mayuri

    It is throwing an error [error] Unknown command: ”

    Reply
  4. The CSS Selector function/method :contains() is not supported by Selenium Webdriver.

    Nor is it supported by Chrome or Firefox
    try using it on their console
    $$(“a:contains(‘Write and Earn’)”)
    it will return an error.

    However the xpath version will work:
    $x(“//a[contains(text(),’Write and Earn’)]”)

    Reply
  5. Hi,
    the section : Syntax

    css=

    # – Symbolic notation to match a string using suffix ”
    has to be corrected.

    Confused with $ and # for match a suffix notation.
    Thanks in advance

    Regards,
    Ashwini

    Reply
  6. @Shilpa

    Thats a nice question.
    There is obviously a preference order in which we tempt to use these elements

    – IDs are considered to be the most reliable locator type as they are unique but they doesn’t work well if the ids are dynamic.
    – Links are also reliable but can only be used with anchor tags.
    – Xpaths are reliable and can easily locate elements but they tend to be slower than other locator types.
    – CSS Selectors are faster than Xpaths but are complex to create.

    Thus, people widely uses Xpaths and cssSelector because of their flexibility..

    Reply
  7. Hello Shruti,

    As you have explained in “CSS selector: Attribute” that defining it as “css=input[type=’submit’] in target field will find the web element,I tried it but it is not identifying web element . Can you please suggest what could be my mistake.

    Thanks,
    Ruchi

    Reply
  8. While recording the value through the Automation tool, I need to select the value from Intellicence. However, the ID, XPath or CSS selector in inspect element is becoming dynamic. So, I’m unable to select the value. Please help me out.

    Reply
  9. @writer

    Yes google page has changed but u can still work by adding few more steps. I am using it like:

    Command Target Value

    assertTitle Sign in – Google Accounts
    type id=Email InvalidEmailID
    click id=next
    waitForPageToLoad
    waitForElementPresent id=Passwd

    type id=Passwd InvalidPassword

    click id=signIn

    I am not sure if this is correct but it works for me.

    Thanks,
    Ruchi

    Reply
  10. @Zoltan

    Thank you for your kind words.
    You can find the information related to Xpaths in the previous tutorial.

    Reply
  11. ${AcctNum} Select Fields From Input Sheet InputSheet1.xls Oct_R1 acc
    ExcelLibrary.Open Excel ${FRAMEWORK_PATH_RESOURCES}${fileName}
    Log ${TEST_NAME}
    ${accountNum}= Get Data From Excel with given row ${sheetName} ${TEST_NAME} ${columnName}

    ${colCount} Get Column Count ${sSheetName}
    ${colNum} Set Variable -1
    : FOR ${y} IN RANGE 0 ${colCount}
    ${header} Read Cell Data By Coordinates ${sSheetName} ${y} 0
    #Check if this is the given header
    Run Keyword If “${header}”==”${sColumnName}” Set Test Variable ${colNum} ${y}
    ${iTotalRows} ExcelLibrary.Get Row Count ${sSheetName}
    : FOR ${iRowNo} IN RANGE 0 ${iTotalRows}
    ${TC_Num} Read Cell Data By Coordinates ${sSheetName} 0 ${iRowNo}
    #Incase TestCase No is same , fetch the data from same row and given column No
    ${sSearchedData} Run Keyword If “${sTestCaseNo}”==”${TC_Num}” ExcelLibrary.Read Cell Data By Coordinates ${sSheetName} ${colNum} ${iRowNo}
    Run Keyword If “${sTestCaseNo}”==”${TC_Num}” Exit For Loop

    Reply
  12. Hi,
    The content :Example for match sub string
    In the syntax “* ” used but when come to example it is explained with “#”.

    Reply
  13. Best thing about your tutorial is you are covering end to end every topic. like you told all options inside Selenium IDE. Now shared details on all types of CSS locators

    Reply
  14. Hi Shruti,

    Great job!!! I am enjoying it a lot. Would you go into the complex concepts of Selenium so that we can become proficient in working with selenium at workplaces?
    Syntax before ‘CSS Selector: Inner text’ needs to be corrected. It is the same as ‘Match the suffix’.

    Thank you once again for all these nice tutorials.

    Reply
  15. The Google sign in GUI has changed so much this tutorial was written. The URLs for the Password page is very long and when I copy/paste it into Selenium IDE Base URL textbox and try to find the css=input#Passwd[name=’Passwd’] element, I get the following error in the log:

    [error] locator not found: css=input#Passwd[name=’Passwd’]

    Anyone else experiencing this?

    Reply
  16. I want to test our website with 20-30 email ids.How do I do the same on selenium IDE(in firefox). those this IDE gives facilities.to extract “username” and password from “excel sheet”
    please help me.

    Reply
  17. Yes, you are right ‘Writer’. Google page is changed, I have used yahoo for testing this tutorial tips.

    Logic remains the same however

    Reply
  18. Is there any .jar file for 64-bit operating system, for launching Chrome browser in selenium ?
    or Same file which is used in 32-bit operating system can used ?

    Reply

Leave a Comment