"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > CSS attribute selector: Use quotes or not?

CSS attribute selector: Use quotes or not?

Posted on 2025-04-13
Browse:485

CSS Attribute Selectors: To Quote or Not to Quote?

Attribute Selectors in CSS: Quotation Mark Conundrum

When crafting CSS attribute selectors to match elements' attributes, such as a[rel="nofollow"], a persistent dilemma arises: whether or not to include quotation marks.

The Quotation Question

The CSS specification dictates guidelines for attribute selector syntax, including the placement of quotation marks around attribute values.

Are Quotation Marks Necessary?

Generally, quotation marks are not required if the attribute value consists solely of alphanumeric characters. However, exceptions exist for:

  • Values containing whitespace (e.g., a[title=My Page])
  • Values containing characters special to CSS syntax (e.g., asterisks, parentheses, etc.)
  • Values starting with a hyphen (e.g., a[class=invalid-class])

Examples of Valid Selectors

Based on the aforementioned rules, the following attribute selectors are considered valid:

a[rel="nofollow"]
a[href^="http://"]
a[data-id='123']

Best Practice

While quotations are optional for alphanumeric values, it is considered best practice to include them to ensure consistency and prevent potential conflicts.

Resources

For a thorough analysis of this topic, refer to:

  • [Unquoted Attribute Values in HTML and CSS](link provided in answer)
  • [Unquoted Attribute Value Validator](link provided in answer)
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3