This CSS selectors cheat sheet lists the selectors you use every day, from classes and IDs to combinators, attribute selectors, and pseudo-classes. To tidy your stylesheet afterwards, use the CSS Beautifier or CSS Minifier.
Basic selectors
| Selector | Matches |
|---|---|
p | Every element of that type |
.class | Elements with that class |
#id | The element with that id |
* | Every element |
a, p | Either selector (grouping) |
Combinators
| Selector | Matches |
|---|---|
div p | p anywhere inside div (descendant) |
div > p | p that is a direct child of div |
h2 + p | p immediately after an h2 |
h2 ~ p | every p that follows an h2 |
Attribute selectors
| Selector | Matches |
|---|---|
[type] | Has the attribute |
[type="text"] | Attribute equals a value |
[href^="https"] | Value starts with |
[href$=".pdf"] | Value ends with |
[class*="btn"] | Value contains |
Pseudo-classes and elements
| Selector | Matches |
|---|---|
:hover | On mouse over |
:focus | The focused element |
:first-child | First child of its parent |
:nth-child(2n) | Every second child |
:not(.x) | Everything except .x |
::before | Inserted content before |
::after | Inserted content after |
Free CSS tools
Frequently asked questions
What is the difference between a class and an id selector?
A class with a dot can be used on many elements, while an id with a hash should be unique to one element on the page.
What does the > combinator do?
It selects only direct children, so div > p matches a p that sits immediately inside the div, not deeper.
What is the difference between :nth-child and :first-child?
:first-child matches only the first, while :nth-child takes a formula like 2n to match a pattern of positions.