Selectors Basics
CSS · Reference cheat sheet
Selectors Basics
CSS · Reference cheat sheet
📋 Overview
Selectors choose which HTML elements a rule applies to. Start with type, class, and id selectors, then combine them. Keep selectors short and readable.
🔧 Core concepts
| Selector | Example | Matches |
|---|---|---|
| Type | p | All <p> elements |
| Class | .card | class="card" |
| Id | #main | id="main" (one per page) |
| Descendant | nav a | a inside nav |
| Child | ul > li | Direct child only |
| Group | h1, h2 | Both h1 and h2 |
| Universal | * | Everything (use sparingly) |
Classes are the workhorse of maintainable CSS.
💡 Examples
Type and class:
h1 {
font-size: 2rem;
}
.note {
padding: 1rem;
background: #eef2ff;
}<h1>Title</h1>
<p class="note">Remember selectors.</p>Descendant vs child:
article p {
margin-bottom: 0.75rem;
}
ul > li {
list-style: disc;
}Grouping and multiple classes:
h1,
h2,
h3 {
line-height: 1.2;
}
.btn.primary {
background: #2563eb;
color: white;
}<button class="btn primary">Save</button>⚠️ Pitfalls
#idis very specific — overuse makes overrides painful.div div div spanselectors are brittle; prefer classes.- Forgetting the
.in.classstyles a non-existent<class>element type. ul > lidoes not match nestedlideeper than one level.