Little Web Hut
(Cascading Style Sheets) CSS 2.1 Reference

CSS Selectors

What is a CSS Selector?

When a style is declared, there must be a method for selecting the element(s) that will receive the style. This is the role of the selector. Selectors are used to match one or more elements. The selector occurs immediately before the style declaration block as shown in the following diagram.

css declaration

For this sample, the selector matches the <div> element by specifying the element's name. The CSS margin and text-align properties will be applied to all of the <div> elements. We could, however, select all elements by replacing the div selector with an asterisk (*). An asterisk matches all elements. Specifically naming an element, or using an asterisk, are just two of the many selector types that can be used for selecting elements. Various other selector types are shown below.

 

CSS Selector Types

Selector
What to Match
Universal Selector ( * ) All elements.
Type Selector ( name ) The name of an element (tag name).
Class Selector ( .classvalue ) The value of an element's class attribute.
ID Selectors ( #idvalue ) The value of an element's id attribute.
Descendant Selectors ( ancestor descendant ) An element that is a descendant of another element.
Child Selectors ( parent > child ) An element that is a child of another element.
Adjacent Sibling Selectors ( first + second ) An element that immediately follows a sibling element.
Pseudo-class ( :first-child ) An element that is a first child.
Pseudo-class ( :link ) A link that has not been visited.
Pseudo-class ( :visited ) A link that has been visited.
Pseudo-class ( :hover ) An element when a mouse cursor is hovering over it.
Pseudo-class ( :active ) An active element.
Pseudo-class ( :focus ) An element with focus.
Pseudo-class ( :lang( ) ) An element with a specific language.
Pseudo-element ( first-line ) The first line of an element.
Pseudo-element ( :first-letter ) The first letter of the first line of text.
Pseudo-element ( :before ) Allows content to be generated before the specified element.
Pseudo-element ( :after ) Allows content to be generated after the specified element.
Attribute Selector [AttributeName] An element with a specific attribute set.
Attribute Selector [AttributeName=AttributeValue] An element with a specific attribute set to a specific value.
Attribute Selector [AttributeName~=AttributeValue] An element with a whitespace separated list attribute that contains a specific value.
Attribute Selector [AttributeName|=AttributeValue] An element where the specified attribute is either equal to a specific value or begins with a specific value followed by a hyphen.