Think of CSS Selectors as a search engine for your HTML. They allow you to find specific elements and apply visual rules to them. Without a solid understanding of selectors, your CSS will become a repetitive mess.
These are the fundamental ways to pick elements based on their name, class, or unique identity.
| Selector | Syntax | Example & Use Case |
|---|---|---|
| Universal | * |
* { margin: 0; } - Resets all elements. |
| Element | tag |
p { line-height: 1.5; } - Styles all paragraphs. |
| Class | .name |
.btn { border: none; } - Styles reusable components. |
| ID | #name |
#navbar { position: fixed; } - Styles one unique element. |
Combinators explain the relationship between two selectors. They are used when you want to style an element only if it resides within a specific parent or follows another element.
These allow you to style elements based on the presence or value of an HTML attribute (like type, href, or target).
Pseudo-classes style an element's state (hover, focus), while pseudo-elements style a specific part of an element (like the first letter).
| Type | Selector | Result |
|---|---|---|
| Pseudo-Class | :hover |
Styles when user hovers mouse. |
| Pseudo-Class | :nth-child(2n) |
Styles every even row (useful for tables). |
| Pseudo-Element | ::before |
Inserts content before the element. |
| Pseudo-Element | ::placeholder |
Styles the hint text inside inputs. |