Selectors Part 1

I will be using the official, boring document from W3 to grab the most current information on css selectors for us. Going to their website won’t really add any beneficial information once this three part guide is finished unless you enjoy reading massive blocks of text.

If you understand this statement well, I wouldn’t bother reading this lesson.

Selectors define the following function:
expression ∗ element → boolean

That is, given an element and a selector, this specification defines whether that element matches the selector.

A selector is a chain of one or more sequences of simple selectors separated by combinators. One pseudo-element may be appended to the last sequence of simple selectors in a selector.

Syntax Selector Table

Valid Selectors

1
2
3
h1 { font-family: sans-serif }
h2 { font-family: sans-serif }
h3 { font-family: sans-serif }

Also Valid Selectors

1
h1, h2, h3 { font-family: sans-serif }

Not a Valid Selector

1
h1, h2..foo, h3 { font-family: sans-serif }

The last example is not a valid selector because it has incorrect syntax. Had the class been h2.foo or just .foo, it would have been fine, but because it was using a double period, it makes that entire statement invalid.

Disclaimer: All Selectors syntax is case-insensitive

Unique Examples:

The following selector represents an HTML object, referencing an image:
object[type^="image/"]

The following selector represents an HTML anchor a with an href attribute whose value ends with “.html”.
a[href$=".html"]

The following selector represents an HTML paragraph with a title attribute whose value contains the substring “hello”
p[title*="hello"]

————————————————-

Old CSS2 Attribute Selectors

[att]
Represents an element with the att attribute, whatever the value of the attribute.

[att=val]
Represents an element with the att attribute whose value is exactly “val”.

[att~=val]
Represents an element with the att attribute whose value is a whitespace-separated list of words, one of which is exactly “val”. If “val” contains whitespace, it will never represent anything (since the words are separated by spaces). Also if “val” is the empty string, it will never represent anything.

[att|=val]
Represents an element with the att attribute, its value either being exactly “val” or beginning with “val” immediately followed by “-” (U+002D). This is primarily intended to allow language subcode matches.