CSS attribute selectors: The rules on quotes (", ' or none?)
This question has been bugging me for a while now. When writing a CSS selector that compares against an element's attribute like so.
a[rel="nofollow"]
I never know what I should be doing with the quotation marks. Are they really necessary?
Basically, what is the specification for this because I can't find it on the web site.
Are all of these considered valid?
a[rel="nofollow"]
a[rel='nofollow']
a[rel=nofollow]
Solution 1:
I’ve written more extensively on the subject here: Unquoted attribute values in HTML and CSS.
I’ve also created a tool to help you answer your question: http://mothereff.in/unquoted-attributes
You can usually omit the quotes as long as the attribute value is alphanumeric (however, there are some exceptions — see the linked article for all the details). Anyhow, I find it to be good practice to add the quotes anyway in case you need them, i.e. a[href^=http://]
won’t work, but a[href^="http://"]
will.
The article I mentioned links to the appropriate chapters in the CSS spec.
Solution 2:
Attribute values must be identifiers or strings
— http://www.w3.org/TR/CSS2/selector.html#attribute-selectors
The first two use strings. The third uses an identifier.
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.
— http://www.w3.org/TR/CSS2/syndata.html#value-def-identifier
Strings can either be written with double quotes or with single quotes.
— http://www.w3.org/TR/CSS2/syndata.html#strings