What is a selector?

A CSS selector is the first part of a CSS Rule. It is a pattern of elements and other terms that tell the browser which HTML elements should be selected to have the CSS property values inside the rule applied to them.

If you have more than one thing which uses the same CSS then the individual selectors can be combined into a selector list so that the rule is applied to all of the individual selectors. See the following code:

h1, .class {
color: blue;
}

There is a wide variety of CSS selectors available, allowing for fine-grained precision when selecting elements to style.

Type class and ID selectors

A type selector selects an HTML tag/element in your document. Type selectors are not case-sensitive.

The universal selector is indicated by an asterisk (*). It selects everything in the document.

The class selector will select everything in the document with that class applied to it. The case-sensitive class selector starts with a dot (.) character.

ID selectors can select an element that has the id set on it, and you can precede the ID with a type selector to only target the element if both the element and ID match. For example:

#one {
background-color: yellow;
}

h1#heading {
color: blue;
}
Attribute selectors

These selectors enable the selection of an element based on the presence of an attribute alone (for example href), or on various different matches against the value of the attribute.

Type of attribute selectors:

[attr]
[attr=value]
[attr~=value]
[attr|=value]

Substring matching selectors

These selectors allow for more advanced matching of substrings inside the value of your attribute.

Examples:

[attr^=value]
[attr$=value]
[attr*=value]
Pseudo-classes and pseudo-elements

A pseudo-class is a selector that selects elements that are in a specific state, e.g. they are the first element of their type, or they are being hovered over by the mouse pointer.

Some pseudo-classes:

:first-child
:last-child
:only-child
:invalid
:focus (user-action pseudo-class)

Pseudo-elements behave in a similar way, however they act as if you had added a whole new HTML element into the markup, rather than applying a class to existing elements.

Combinators

Combinators combine other selectors in a way that gives them a useful relationship to each other and the location of content in the document.

Some types of combinators:

descendant
child
next-sibling
subsequent-sibling