CSS attribute selectors: The rules on quotes (", ' or none?)

CssStringCss Selectors

Css Problem Overview


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]

Css Solutions


Solution 1 - Css

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

Unquoted attribute value validator

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 - Css

> 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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOlicalView Question on Stackoverflow
Solution 1 - CssMathias BynensView Answer on Stackoverflow
Solution 2 - CssQuentinView Answer on Stackoverflow