Code Reference

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

SelectorExampleMatches
TypepAll <p> elements
Class.cardclass="card"
Id#mainid="main" (one per page)
Descendantnav aa inside nav
Childul > liDirect child only
Grouph1, h2Both 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

  • #id is very specific — overuse makes overrides painful.
  • div div div span selectors are brittle; prefer classes.
  • Forgetting the . in .class styles a non-existent <class> element type.
  • ul > li does not match nested li deeper than one level.

On this page