Selectors (CSS)
An overview of CSS selectors and how to combine them
Selector types
Type selector
Selects based on HTML element type
Universal selector
Selects all elements
Class selector
Selects elements based on class
ID selector
Selects elements based on ID
Attribute selector
Select elements based on attributes
Pseudo-class selector
Selects elements that are in a specific state
Typically combined with other selectors (see also below)
Special case: the negation pseudo-class
Pseudo-element selector
Selects specific part of an element
Typically combined with other selectors
Combining selectors
,
Selector lists using No effect other than reducing code duplication
Example: before
Example: after
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
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
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
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
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