Do values in CSS attribute selector values need to be quoted?

前端 未结 4 1508
感情败类
感情败类 2020-12-18 05:55

e.g.:

a[href=\"val\"]

Does \"val\" need to have quotes around it? Single or double are acceptable? What about for integers?

4条回答
  •  囚心锁ツ
    2020-12-18 06:27

    TLDR: Quotes are required unless the value meets the identifier specification for CSS2.1

    The CSS spec might say they are optional, but the real world presents a different story. When making a comparison against the href attribute you will need to use quotes (single or double work in my very limited testing - latest versions of FF, IE, Chrome.)

    Interestingly enough the css spec link referenced by @Pekka happens to use quotes around their href-specific examples.

    And it's not just due to non-alpha characters like the period or slashes that give this unique situation a quote requirement - using a partial match selector ~= doesn't work if you just use the "domain" in "domain.com"

    Ok, every answer here is wrong (including my own previous answer.) The CSS2 spec didn't clarify whether quotes are required in the selector section itself, but the CSS3 spec does and quotes the rule as a CSS21 implementation:

    http://www.w3.org/TR/css3-selectors/

    Attribute values must be CSS identifiers or strings. [CSS21] The case-sensitivity of attribute names and values in selectors depends on the document language.

    And here is the identifier info:

    http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier

    In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B\&W\?" or "B\26 W\3F".

    My answer seemed correct but that's because the '~=' is a white-space selector comparator so it will never match a partial string inside an href value. A '*=' comparator does work however. And a partial string like 'domain' does work for matching href='www.domain.com'. But checking for a full domain name would not work because it violates the identifier rule.

提交回复
热议问题