CSS Selectors
CSS selectors are a fundamental part of Cascading Style Sheets (CSS), a stylesheet language used for describing the presentation and formatting of web documents, such as HTML and XML. CSS selectors are used to target specific HTML elements within a web page, allowing you to apply styles (e.g., colors, fonts, margins, and more) to those elements.
Selectors work by selecting one or more HTML elements based on various criteria, like element types, attributes, and their hierarchical relationships within the document. Below you will find a list of CSS selectors.
Selector | Example | Example Description | CSS |
---|---|---|---|
Universal | * | Styles all elements | 2 |
.class | .intro | Styles all elements with class="intro" | 1 |
#id | #list | Styles the element with id="list" | 1 |
Type Selector | ul | Styles all <ul> elements | 1 |
Selector list | div, p | Styles all <div> elements and all <p> elements | 1 |
Descendant combinator | div p | Styles all <p> elements inside <div> elements | 1 |
Child combinator (>) | div > p | Styles all <p> elements where the parent is a <div> element | 2 |
Adjacent sibling combinator (+) | div + p | Styles all <p> elements that are placed immediately after <div> elements | 2 |
General sibling combinator | p ~ ul | Styles every <ul> element that are preceded by a <p> element | 3 |
[attribute] | [target] | Styles all elements with a target attribute | 2 |
[attribute=value] | [target=_blank] | Styles all elements with target="_blank" | 2 |
[attribute~=value] | [title~=America] | Styles all elements with a title attribute containing the word "America" | 2 |
[attribute|=value] | [lang|=en] | Styles all elements with a lang attribute value starting with "en" | 2 |
[attribute^=value] | a[title^="A"] | Styles every <a> element whose title attribute value begins with "A" | 3 |
[attribute$=value] | a[title$="ca"] | Styles every <a> element whose title attribute value ends with "ca" | 3 |
[attribute*=value] | a[title*="America"] | Styles every <a> element whose title attribute value contains the substring "America" | 3 |