Font Awesome Free 5.13.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
Skip to main content

Selectors (CSS)

An overview of CSS selectors and how to combine them

Selector types

Type selector

Selects based on HTML element type

h1 {
color: red;
}

Universal selector

Selects all elements

* {
color: red;
}

Class selector

Selects elements based on class

.error-text {
color: red;
}

ID selector

Selects elements based on ID

#main-text {
color: black;
}

Attribute selector

Select elements based on attributes

[disabled] {
color: red;
}

Pseudo-class selector

Selects elements that are in a specific state

Typically combined with other selectors (see also below)

a:hover {
color: red;
}
Pseudo-classes reference

Special case: the negation pseudo-class

/* matches any element that is not a paragraph */
:not(p) {
color: blue;
}

Pseudo-element selector

Selects specific part of an element

Typically combined with other selectors

p::first-line {
text-transform: uppercase;
}
Pseudo-elements reference

Combining selectors

Selector lists using ,

No effect other than reducing code duplication

Example: before

h1 { 
color: blue;
}

.special {
color: blue;
}

Example: after

h1, .special { 
color: blue;
}

Same-element combinations

Combine multiple selectors that all need to apply to the same element

Example: select all hyperlinks with class test that the user hovers over

a.test:hover {
color: red;
}

Descendant combinator

Typically represented by a single space ( ) character

Elements matched by the second selector are selected if they have an ancestor matching the first selector

Example: select all spans that are directly or indirectly inside a div with class test

div.test span {
color: red;
}

Child combinator

Represented by the > sign

Same as descendant combinator, but only considers the direct parent of an element

Example: select all spans that are a direct child of a div with class test

div.test > span {
color: red;
}

Adjacent sibling combinator

Represented by the + sign

Matches an element matching the second selector if that element immediately follows an element matching the first selector and they both have the same parent

Example: select all paragraphs that immediately follow an image

img + p {
color: red;
}

General sibling combinator

Represented by the ~ sign

Matches an element matching the second selector if that element follows an element matching the first selector (but not necessarily immediately) and they both have the same parent

Example: select paragraphs that come after any image with the same parent

img ~ p {
color: red;
}

Resources