What is a CSS Selector?

Beginning CSS

CSS
Wikimedia Commons

CSS relies on pattern matching rules to determine which style applies to which element in the document. These patterns are called selectors and they range from tag names (for example, p to match paragraph tags) to very complicated patterns that match very specific parts of a document (for example, p#myid > b.highlight would match any b tag with a class of highlight that is a child of the paragraph with the id myid).

A CSS selector is the part of a CSS style call that identifies what part of the web page should be styled. The selector contains one ore more properties that define how the selected HTML will be styled.

The CSS Selectors

There are several different types of selectors:

  • type selectors—matching a specific element
  • class selectors—matching elements with a specific class
  • ID selectors—matching the element with a specific ID
  • descendant selectors—matching elements that are descendants of a specific element
  • child selectors—matching elements that are a child of the specific element
  • universal selectors—matching any element
  • adjacent sibling selectors—matching elements immediately preceded by a specific element
  • attribute selectors—matching elements with a specific attribute or attribute value
  • pseudo-class selectors—matching elements with a specific pseudo class
  • pseudo-element selectors—matching elements with specific pseudo-element properties

    Format CSS Styles and CSS Selectors

    The format of a CSS style looks like this:

    selector { style property : style ; }

    Separate multiple selectors that have the same style with commas. This is called selector grouping. For example:

    selector1, selector2 { style property : style ; }

    Grouping selectors is a shorthand mechanism to keep your CSS styles compact.

    The above grouping would have the same effect as:

    selector1 { style property : style ; }
    selector2 { style property : style ; }

    Always Test Your CSS Selectors

    Not all browsers support all the CSS selectors. So be sure to test your selectors in as many browsers on as many operating systems as you can. But if you are using CSS 1 or CSS2 selectors you should be fine.