CSS Selector Cheat Sheet
In CSS, selectors are patterns to identify which DOM elements a style is being applied to. In the following example, h1 and img are selectors for corresponding styles.
1 | h1 { font-size: 36px; } |
There are plenty of selectors available in CSS, here is a cheat sheet of most common ones:
| Syntax | Example | Description |
|---|---|---|
<tag-name> |
h1 |
selects all |
.<class-name> |
.theme-title |
selects all elements with class |
#<element-id> |
#nav |
selects (all) elements with id |
[<attr>=<value>] |
[disabled=true] |
selects all element with attribute |
:<state> |
:hover |
selects all elements are being hovered. Other states |
Occasionally, you will be using selectors in combination, such as:
| Syntax | Description and Examples |
|---|---|
<selector-1><selector-2> |
selects all elements matched |
<selector-1>,<selector-2> |
selects all elements matched |
<selector-1> <selector-2> |
selects all elements matched |
<selector-1> > <selector-2> |
selects all elements matched |
<selector-1> + <selector-2> |
selects the first element matched |
Even more, you would probably use pseudo-selectors for conditionally selecting elements as below:
| Syntax | Description and Examples |
|---|---|
:first-child |
selects the first child of an element, e.g |
:last-child |
selects the last child of an element, e.g |
:not(<selector>) |
selects all elements that not matched |
:nth-child(<pat>) |
selects all child elements matched the |
::before |
adds content before an element, e.g |
::after |
adds content after an element, e.g |