Selectors = patterns used to select which element(s) to style.
Use W3Schools' CSS Selector Tester to demonstrate the different selectors.
| Selector | Example | Description |
|---|---|---|
| .class | .name | Selects all elements with class="name" |
| .class1.class2 | .name1.name2 | Selects all elements with both name1 and name2 set within its class attribute |
| .class1 .class2 | .name1 .name2 | Selects all elements with name2 that is a descendant of an element with name1 |
| #id | #name | Selects the element with id="name" |
| * | * | Selects all elements |
| element | p | Selects all <p> elements |
| element.class | p.name | Selects all <p> elements with class="name" |
| element, element | div, p | Selects all <div> elements and all <p> elements |
| element element | div p | Selects all <p> elements inside <div> elements |
| element > element | div > p | Selects all <p> elements where the parent is a <div> element |
| element + element | div + p | Selects all <p> elements that are placed immediately after <div> elements |
| element1 ~ element2 | p ~ ul | Selects every <ul> element that are preceded by a <p> element with the same parent |
| [attribute] | [target] | Selects all elements with a target attribute (e.g.) |
| [attribute=value] | [target=_blank] | Selects all elements with target="_blank" (e.g.) |
| [attribute~=value] | [title~=flower] | Selects all elements with a title attribute containing the word "flower" |
| [attribute|=value] | [lang|=en] | Selects all elements with a lang attribute value starting with "en" (e.g.) |
| [attribute^=value] | a[href^="https"] | Selects every <a> element whose href attribute value begins with "https" |
| [attribute$=value] | a[href$=".pdf"] | Selects every <a> element whose href attribute value ends with ".pdf" |
| [attribute*=value] | a[href*="example"] | Selects every <a> href attribute value contains the substring "example" |
| :active | a:active | Selects the active link |
| ::after | p::after | Insert something after the content of each <p> element |
| ::before | p::before | Insert something before the content of each <p> element |