Updated June 29, 2026
CSS selectors cheat sheet
Selectors decide which elements a CSS rule applies to. They range from simple type and class selectors to combinators and pseudo-classes that match by relationship or state.
Basic selectors
| Selector | What it matches |
|---|---|
* | Every element. |
p | All <p> elements (type selector). |
.btn | Elements with class "btn". |
#main | The element with id "main". |
[type="email"] | Elements with that attribute value. |
a, button | Both <a> and <button> (grouping). |
Combinators
| Selector | What it matches |
|---|---|
div p | Any <p> inside a <div> (descendant). |
div > p | A <p> that is a direct child of a <div>. |
h2 + p | The <p> immediately after an <h2>. |
h2 ~ p | All <p> siblings after an <h2>. |
Pseudo-classes
| Selector | What it matches |
|---|---|
:hover | An element under the pointer. |
:focus | A focused element. |
:first-child | The first child of its parent. |
:last-child | The last child of its parent. |
:nth-child(2n) | Every second child. |
:not(.active) | Elements without class "active". |
Pseudo-elements
| Selector | What it matches |
|---|---|
::before | Inserted content before an element. |
::after | Inserted content after an element. |
::placeholder | An input's placeholder text. |
::selection | The portion the user has highlighted. |
Specificity, brieflyWhen rules conflict, more specific selectors win: an id beats a class, which beats a type selector. Keep selectors as simple as the design allows to avoid specificity battles.
References
Questions
What is the difference between a class and an id selector?
A class (.name) can apply to many elements, while an id (#name) should be unique on the page. Ids also have higher specificity, so they override class rules.
What does :nth-child do?
It matches elements by their position among siblings. :nth-child(2n) selects every second element, and :nth-child(3) selects the third.