Friday, March 11, 2016

CSS Selectors Level 3

1. Selector Syntax

Selector

A selector is one or more sequences of simple selectors separated by combinators, an optional pseudo-element may follow the last sequence of simple selectors

selector = sequenceOfSimpleSelectors [combinator1 sequenceOfSimpleSelectors1 ... ] [::pseudoElement]

A sequence of simple selectors

  • it is a chain of simple selectors that are not separated by a combinator
  • it always begins with a type selector or a universal selector. No other type selector or universal selector is allowed in the sequence
  • simple selectors are: type selector, universal selector, attribute selector, class selector, ID selector, pseudo-class.
  • combinators are: whitespace, > "greater-than sign", + "plus sign", ~ "tilde"

The subjects of a selector are the elements of a document tree that are represented by the selector.

2. Simple Selectors

2.1 Type selector (or Tag selector)

A tag selector is the name of an element type

Example

h1 {} /* it selects all h1 elements */

Example

Type selectors and namespaces

Type selectors allow an optional namespace component formed from a namespace prefix and a namespace separator "vertical bar" (|). The namespace prefix has to be previously declared.

Example

@namespace myNs url(http://www.example.com); /* myNs namespace declaration */
  • Elements type selector with namespace component

    myNs|e  /* element e in namespace myNs */
       *|e  /* elements e in any namespace, including those without a namespace */
  • Elements type selector with namespace component but without namespace prefix

        |e  /* elements with name e but with no namespace */
  • Elements type selector without a namespace component

        e   /* equivalent to *|e  (no default namespace declared)
               equivalent to myNs|e (myNs declared as default namespace) */
2.2 Universal Selector

The universal selector is written with an asterisk * and represents the name of any element type.

The universal selector can be omitted in a sequence of simple selectors. The following rules are equivalent:

*.foregroundColorClass { color: #556677; } 
 .foregroundColorClass { color: #556677; }
2.3 Attribute selector

Attribute selectors introduced by CSS2

selectormatched elements
[attr] an element with the attr attribute
[attr=val] an element whose attr attribute whose value is exactly "val"
[attr~=val] an element with the attr attribute whose value is a list of words separated by white space and one of those word is exactly "val".
[attr|=val] an element with the attr attribute, its value either being exactly "val" or beginning with "val" immediately followed by "-" called dash.

Example

/* h1 elements that specifies the "title" attribute */
h1[title] { color: #0000FF; }

/* elements whose "lang" attribute has value "en" */
*[lang=en] { font-style: italic }

/* input elements whose "type" attribute has the value "submit": buttons */
input[type="submit"] { ... }

/* link elements having "rel" attribute whose value is a list containing the "copyright" value */
a[rel~="copyright"] { color: #0000FF } 

/* elements whose "lang" attribute begins with "en", including "en", "en-US", "en-UK" */
*[lang|="en"] { color : #FF0000 }

Example: <input type="text"> elements selector

Attribute selectors introduced by CSS3

selectorelement matched
[att^=val] an element with the "att" attribute whose value begins with the prefix "val"
[att$=val] an element with the "att" attribute whose value ends with the suffix "val"
[att*=val] an element with the "att" attribute whose value contains an occurrence of the substring "val"
2.4 Class (attribute) selector

You can add class attribute to document's element nodes sharing the same style rules has a class attribute in common.

A class selector uses the period (.) notation for representing the class attribute, this is equivalent to [class~=value].

Example: all elements with class~="blueText"

*.blueText { color: #0000FF; }
or
 .blueText { color: #0000FF; }

Example: paragraph elements with class~="rightAlign"

p.redText { color: #CC0000; }

How to apply the .blueText and p.redText rules:

Example: p elements whose class attribute value is a list of whitespace-separated values that includes both redText and centerAlign:

.redText.centerAlign { color: #FF0000; text-align: center; }
2.5 ID (attribute) selector

Document's element nodes may contain an ID attribute. ID attributes are special, because two such attributes cannot have the same value: the ID attribute uniquely identifies its element.

#identifier {}  /* An ID selector contains a "#" followed by the ID value */

Example: select any element whose ID attribute has the value "chapter1"

#chapter1 { text-align: center; }  /* ID general selector */

Example: select an h1 element whose ID attribute has the value "chapter1"

h1#chapter1 { text-align: center; } /* ID specific selector */

There is no need to append the ID selector to an element selector, because the ID is unique. Besides, the general syntax is more useful: when you declare a simple ID selector you assign any document element the ID and you can later change your mind and switch element type to another one, without amending the CSS style sheet.

2.6 Pseudo-classes

The pseudo-class allows selection based on information that depends on the document tree or based on element states.

:pseudoClass[('value')]  /* A pseudo-class consists of a "colon" (:) followed by the name
                            of the pseudo-class and an optional value between parentheses */

Add a pseudo-class in a sequences of simple selectors after the leading type selector or universal selector.

  • Pseudo-classes can be mutually exclusive, while others can be applied simultaneously to the same element.
  • Pseudo-classes may be dynamic, when an element acquire or lose a pseudo-class while a user interacts with the document.
2.6.1 Dynamic pseudo-classes
2.6.1.1 The anchor pseudo-classes: :link and :visited

The anchor element pseudo-classes :link and :visited are mutually exclusive.

2.6.1.2 The user action pseudo-classes :hover, :active and :focus

You may apply user action pseudo-classes to every HTML element a user interacts through mouse, keyboard, etc. They are usually used on links and form controls.

:hover

a browser applies the :hover pseudo-class when the cursor hovers over a box generated by the element

:active

a browser applies the :active pseudo-class while an element is being activated by the user, for example between the times the user clicks and releases the main mouse button on that element.

:focus

A browser applies the :focus pseudo-class to an element that accepts events from input devices while that element has the focus.

Note: do not confuse :focus with :selected of jQuery: a page has only an element with focus, a <select> element can have multiple options selected.

Example: pseudo-classes on links must be declared in the following order:

a:link    /* unvisited links */
a:visited /* visited links */
a:hover   /* user hovers */
a:active  /* active links */

Example: dynamic pseudo-classes

2.6.2 The target pseudo-class

URIs that refers to a location within a document ends with a # followed by an anchor identifier (called the fragment identifier). The element linked by the fragment is known as the target element. (The character # is known as number sign in US and hash sign in EU).

:target

A browser applies the :target pseudo-class to a link's target element when the user clicks on the link.

Example: :target pseudo-class for outlining h3 heading

See the Pen CSS3 selectors :target pseudoclass for outlining elements by Massimiliano (@maxdesimone) on CodePen.

2.6.3 The language pseudo-class
:lang(xx)

the pseudo-class :lang(xx) represents an element that is in language xx. An element in language xx is an element whose lang attribute value is a equal to xx or to a string beginning with xx a followed by an hyphen "-", the match is not case sensitive.

Example - :lang pseudo-class with paragraph elements

See the Pen CSS3 selectors :lang pseudoclass by Massimiliano (@maxdesimone) on CodePen.

2.6.4 The UI element states pseudo-classes

The UI User Interface pseudo-classes match states of form elements.

2.6.4.1 The :enabled and :disabled pseudo-classes
:enabled

The :enabled pseudo-class match UI elements that are in an enabled state

:disabled

The :disabled pseudo-class match UI elements that are in a disabled state

Note: display and visibility CSS properties have no effect on the enabled/disabled state of an element.

2.6.4.2 The :checked pseudo-class

The :checked pseudo-class applies to radio and checkbox elements switched on by the user.

2.6.5 Structural pseudo-classes

Structural pseudo-classes select nodes based on document tree information. When calculating position of an element in the list of children the index numbering starts at 1, not counting any non-element nodes.

Structural Pseudo-classes
selectormatching element
:rootthe root element of the document
:nth-child(an+b) a child element that has an+b-1 siblings before it in the document tree
:nth-last-child(an+b) a child element that has an+b-1 siblings after it in the document tree
:nth-of-type(an+b) a child element that has an+b-1 siblings, with the same name, before it in the document tree.
:nth-last-of-type(an+b) a child element that has an+b-1 siblings, with the same name, after it in the document tree.
:first-child an element that is the first child of some other element.
:last-child an element that is the last child of some other element
:first-of-type an element that is the first sibling of its type in the list of children
:last-of-type an element that is the last sibling of its type in the list of children
:only-child a child element whose parent element has no other element children
:only-of-type a child element whose parent element has no other children with the same element name
:empty an element that has no children at all
with n ∈ ℕ; a,b ∈ ℤ
The :root pseudo-class
:root

The :root pseudo-class represents the root element of the document. In a HTML document, this is always the <HTML> element.

The :nth-child pseudo-class
:nth-child(an+b) where n ∈ ℕ; a,b ∈ ℤ

The :nth-child(an+b) pseudo-class represents a child element that has an+b-1 siblings before it in the document tree

In addition, :nth-child() can take ‘odd’ and ‘even’ as arguments:

  • ‘odd’ has the same signification as 2n+1
  • ‘even’ has the same signification as 2n

Examples, alternate the color of table rows in a cycles:

tr:nth-child(2n+1) /* represents every odd row of an HTML table */
tr:nth-child(odd)  /* same */
tr:nth-child(2n+0) /* represents every even row of an HTML table */
tr:nth-child(even) /* same */

If a≠0 and b=0, it selects every ath element

Examples:

tr:nth-child(2n+0) /* represents every even row of an HTML table */
tr:nth-child(2n)   /* same */

b may have a negative sign

Examples:

:nth-child(10n-1)  /* represents the 9th, 19th, 29th, etc, element */
:nth-child(10n+9)  /* Same */

Examples: nth-child() pseudoclasses with table rows

See the Pen CSS3 Selectors: nt-child() pseudoclasses by Massimiliano (@maxdesimone) on CodePen.

The :nth-last-child pseudo-class
:nth-last-child(an+b) where n ∈ ℕ; a,b ∈ ℤ

The :nth-last-child(an+b) pseudo-class represents a child element that has an+b-1 siblings after it in the document tree. The syntax of its argument is similar to :nth-child() pseudo-class.

Examples:

tr:nth-last-child(-n+2)    /* represents the two last rows of an HTML table */
elem:nth-last-child(odd)   /* represents all odd elem element, counting from the last one */
The :nth-of-type pseudo-class
:nth-of-type(an+b) where n ∈ ℕ; a,b ∈ ℤ

The :nth-of-type(an+b) pseudo-class represents a child element that has an+b-1 siblings with the same name before it in the document tree. The syntax for the arguments is similar to the :nth-child() pseudo-class.

Examples, alternate the position of floated images: < /p>

img:nth-of-type(2n+1) { float: right; }
img:nth-of-type(2n) { float: left; }
The :nth-last-of-type pseudo-class
:nth-last-of-type(an+b) where n ∈ ℕ; a,b ∈ ℤ

The :nth-last-of-type(an+b) pseudo-class represents a child element that has an+b-1 siblings with the same name after it in the document tree. The syntax for the arguments is similar to the :nth-child() pseudo-class.

Examples:

To represent all h2 children of an XHTML body except the first and last, one could use the following selector:

body > h2:nth-of-type(n+2):nth-last-of-type(n+2)

In this case, one could also use :not(), although the selector ends up being just as long:

body > h2:not(:first-of-type):not(:last-of-type)
The :first-child pseudo-class
:first-child

represents an element that is the first child of some other element

:first-child  or
:nth-child(1)

Example: select a P element that is the first child of an article element:

article > p:first-child { }

This selector can represent the p inside the article of the following fragment, but cannot represent the second p in the same fragment:

See the Pen CSS3 :first-child pseudoclass by Massimiliano (@maxdesimone) on CodePen.

The following two selectors are usually equivalent:

* > a:first-child /* a is first child of any element */
a:first-child /* Same (assuming a is not the root element) */
The :last-child pseudo-class
:last-child

represents an element that is the last child of some other element.

:last-child or 
:nth-last-child(1)

Example: a list item li last child of an ordered list ol.

ol > li:last-child

Example: li:first-child and li:last-child pseudoclasses

Within the following unordered the first child element works as heading and the last child element works as footer.

See the Pen CSS3 :first-of-type and :last-of-type pseudoclass by Massimiliano (@maxdesimone) on CodePen.

The :first-of-type pseudo-class
:first-of-type

represents an element that is the first sibling of its type in the list of children

:first-of-type or
:nth-of-type(1)
The :last-of-type pseudo-class
:last-of-type

represents an element that is the last sibling of its type in the list of children

:last-of-type /* or */
:nth-last-of-type(1)

Example:

/* the last data cell of a table row tr */
tr > td:last-of-type
The :only-child pseudo-class
:only-child

represents a child element whose parent element has no other element children.

:only-child /* or */
:first-child:last-child /* or */
:nth-child(1):nth-last-child(1)
The :only-of-type pseudo-class
:only-of-type

represents a child element whose parent element has no other children with the same element name

:only-of-type /* or */
:first-of-type:last-of-type
:nth-of-type(1):nth-last-of-type(1)
The :empty pseudo-class
:empty

represents an element that has no children at all.

Examples: selecting empty P elements

p:empty  /* select all <p></p> */
2.6.6 The negation pseudo-class
:not(<selector>) /* takes a simple selector as argument. */

The negation pseudo-class represents an element that is not represented by its selector argument. Since pseudo-elements are not simple selectors, they are not a valid argument.

body *:not(p) { } /* all body's child elements except P */
body *:not(p.classy) { } /* wrong: argument is not simple selector */

See the Pen CSS3 negation pseudoclass by Massimiliano (@maxdesimone) on CodePen.

3. Pseudo Elements

Pseudo-elements do not represent physical elements in the DOM tree, but create abstractions about the document.

::pseudoElement

A pseudo-element is made of two colons (::) followed by the name of the pseudo-element.

The CSS3 specification introduces the :: notation to distinguish between pseudo-classes and pseudo-elements.

  • Only one pseudo-element may appear per selector and after the sequence of simple selectors.
  • A ::pseudoElement selector does not match any real document element, but browsers will insert a pseudo-element in the HTML document.
3.1 The ::first-line pseudo-element

The ::first-line pseudo-element describes the contents of the first formatted line of an element.

Example: the first line of every paragraph

p::first-line { 
  color: #FF0000;
  font-size: 2em;
  text-transform: uppercase; 
}

The length of the first line may vary depending on a number of factors.

3.2 The ::first-letter pseudo-element

The ::first-letter pseudo-element represents the first letter of an element containing text.

Example: the ::first-letter pseudo-element used for creating the "initial caps" typographical effect.

p::first-letter { 
  font-size: 3em; 
  font-weight: normal; 
  line-height: 0.8; 
}
p { 
  line-height: 1.1; 
}

In CSS, the ::first-letter pseudo-element can be used with block-like containers such as block, list-item, table-cell, table-caption, and inline-block elements. All such elements that contain text.

3.3 The ::before and ::after pseudo-elements

The ::before and ::after pseudo-elements is used to describe generated content before or after an element's content.

Example - insert the quote marks before and after every q (short quote) element:

See the Pen CSS3 selectors: ::before and ::after pseudo-elements by Massimiliano (@maxdesimone) on CodePen.

5. Combinators

5.1 Descendant combinator

Descendant combinators are used to describe an element that is a descendant of another element in the document tree.

A B  /* a descendant combinator is whitespace that 
        separates two sequences of simple selectors */

A selector of the form "A B" represents an element B that is an arbitrary descendant of some ancestor element A.

Examples: an em element descendant of an h1 element

h1 em

<h1> This <span> header is <em> very </em> important </span> </h1>

Example: a p element that is a grandchild or later descendant of a div element

div * p

Example: any element that has the href attribute set and is inside a p that is itself inside a div:

div p *[href]
5.2 Child combinators

A child combinator describes a childhood relationship between two elements.

A > B  /* a child combinator is the "greater-than sign" (>) 
          character that separates two sequences of simple selectors */

Example: a p element that is child of body

body > p
5.3 Sibling combinators

There are two different sibling combinators: the adjacent sibling combinator and the general sibling combinator, text nodes are ignored when considering adjacency.

5.3.1 Adjacent sibling combinator

Two adjacent sibling elements share the same parent in the document tree and the element represented by the first sequence immediately precedes the element represented by the second sequence.

A + B  /* an adjacent sibling combinator is the "plus sign" (+) 
          character that separates two sequences of simple selectors */

Examples:

The following selector represents a p element immediately following a math element:

math + p
5.3.2 General sibling combinator

Two general sibling elements share the same parent in the document tree and the element represented by the first sequence precedes (not necessarily immediately) the element represented by the second sequence.

A ~ B  /* the general sibling combinator is the "tilde sign" (~) 
          character that separates two sequences of simple selectors */

Example: an h2 element following an h1

h1 ~ h2

6. Calculating a selector's specificity

A selector's specificity is calculated as follows:

inline style1000 points
ID selector100 points
class selector, attribute selector, pseudo-class selector10 points
type selector, pseudo-element selector1 point
universal selector0 point

Example

ul {}             /* 1 elem          - specificity = 1   */
ul.menu li { }    /* 2 elem  1 class - specificity = 12  */
#meat_menu li { } /* 1 elem  1 id    - specificity = 101 */

See the Pen CSS3 Selectors: specificity by Massimiliano (@maxdesimone) on CodePen.

No comments :

Post a Comment