selector

Simple selectors

  • * : Universal selector selects all elements.
  • type : Type selector selects all elements of that type. Type refers to the type of tag(e.g. body, div, p…)
  • #id : ID selector selects a single element with a specific id(same as [id=val]).
  • .class : Class selector selects all elements that have a specific class(same as [class~=val]).

Attribute selectors

  • [attr] : Select all elements that have a specific attribute.
  • [attr=val] : Select all elements that have a specific attribute value.
  • [attr^=val] : Select all elements that starts with specific characters.
  • [attr$=val] : Select all elements that ends with specific characters.
  • [attr*=val] : Select all elements that contains with specific characters.
  • [attr~=val] : Select all elements that contains with specific word which space-separated with other characters.
  • [attr|=val] : Select all elements that have a attribute value val or start with val-

Pseudo-classes

  • :hover
  • :focus
  • :not() : except
  • :empty
  • :only-child
  • :only-of-type
  • :first-child
  • :first-of-type
  • :last-child
  • :last-of-type
  • :nth-child()
  • :nth-of-type()
  • :nth-last-child()
  • :nth-last-of-type()
How "nth" work with arguments?
   2   : second one    (index start with 1)
   even: even ones
   odd : odd ones
   n   : 0, 1, 2, 3... (everyone)
   n+4 : 4, 5, 6...    (>=4)
   -n+4: 4, 3, 2, 1... (<=4)
   3n  : 0, 3, 6...    (every 3)
   3n+5: 5, 8, 11...   (from 5 every 3)

Pseudo-elements

  • ::before : work like first child(must set content to take effect)
  • ::after : work like last child(must set content to take effect)
  • ::first-letter
  • ::first-line
  • ::selection

Selector lists and Combinators

  • , : Selector list (or)
  • > : Child combinator (child)
  • space : Descendant Selector (child, grandchild…)
  • + : Adjacent sibling combinator (next sibling)
  • ~ : General sibling combinator (next sibling, next next sibling…)

Reference

  1. w3schools - CSS Selector Reference
  2. CSS Diner - Where we feast on CSS Selectors!
  3. 30個你必須記住的CSS選擇器
  4. CSS|MDN