CSS3 Selectors

CSS3 provides three new attribute selectors and one new combinator – that is, a selector that joins other selectors together, such as the child or descendant combinators from CSS2. These selectors are defined in Selectors Level 3 Module, which currently has the status of Proposed Recommendation. This status means the module is widely accepted and is implemented by major browsers.

CSS3 Attribute Selectors

In CSS 2 we had following four attribute selectors defined –

  • /* Simple Attribute Selector */
  • E[attr] { }
  • /* Exact Attribute Value Selector */
  • E[attr = ‘value’]
  • /* Partial Attribute Value Selector */
  • E[attr ~= ‘value’]
  • /* Language Attribute Selector */
  • E[attr|=’value’]
And the new three CSS3 Attribute Selectors are –

  • /* Represents an element with the ‘attr’ attribute whose value begins with the prefix “value” */
  • E[attr ^= 'value']
  • /* Represents an element with the ‘attr’ attribute whose value ends with the prefix “value”*/
  • E[attr$='value' ]
  • /* Represents an element with the ‘attr’ attribute whose value contains at least one instance of the substring “value”.*/
  • E[attr*= 'value' ]

CSS3 Combinator

In CSS2 we had one combinator defined –

  • /* Adjacent Sibling Combinator */
  • E + F
And the new combinator defined in CSS3 is

  • /*General Sibling Combinator */
  • E ~ F

The difference between above two combinator is subtle but important. Adjacent Sibling selects any element (F) that is immediately preceded by element (E) on the same level of the document tree, but General Sibling selects any element (F) that is preceded by element (E) on the same level of the tree, regardless of whether it is immediately adjacent.

In Action

Navigate to jsfiddle site by clicking [+] to explore the HTML and CSS code of below example.

Selectors: Browser Support

Webkit Firefox Opera IE
Attribute Selectors Yes Yes Yes Yes
General Sibling Combinator Yes Yes Yes Yes

Source

a) The Book of CSS3: A Developer’s Guide to the Future of Web Design

b) Selectors Level 3 – w3.org