Code Reference

Selectors

CSS · Reference cheat sheet

Selectors

CSS · Reference cheat sheet


📋 Overview

Selectors target elements for styling. From type/class/id to attributes, combinators, and modern relational selectors (:is, :where, :has). Write selectors that express intent without over-specificity.

🔧 Core concepts

KindExample
Type / class / iddiv .card #app
Attribute[type="text"] [data-x]
CombinatorsA B A > B A + B A ~ B
Pseudo-class:hover :nth-child :focus-visible
Pseudo-element::before ::placeholder
Groupingh1, h2 / :is(h1, h2)
Relatival:has(> img)
  • :where(): specificity 0; :is(): takes most specific argument.
  • Universal: * — use sparingly.
  • Namespace: svg|a rare in HTML docs.
nav > ul > li + li {
  margin-left: 1rem;
}
article:has(img) {
  display: grid;
}

💡 Examples

/* Attributes */
a[target="_blank"]::after {
  content: "↗";
}
input[type="checkbox"]:checked + label {
  font-weight: 600;
}

/* Structural */
tr:nth-child(even) {
  background: #f6f6f6;
}
li:not(:last-child) {
  border-bottom: 1px solid #ddd;
}

/* Soft specificity */
:where(.prose) a {
  color: var(--link);
}
:is(h1, h2, h3):hover {
  text-decoration: underline;
}

/* Has */
label:has(:invalid) {
  color: crimson;
}
.card:has(> .badge) {
  padding-top: 2rem;
}

/* Focus */
:focus-visible {
  outline: 2px solid var(--accent);
  outline-offset: 2px;
}
/* Avoid over-qualification */
/* BAD: div.card.panel */
/* GOOD: .card */

⚠️ Pitfalls

  • IDs (#x) crush specificity — prefer classes for UI.
  • Descendant selectors (A B) are costly when very broad on large DOMs — tighten when needed.
  • :has() is powerful but can be expensive — avoid pathological deep queries.
  • ::before needs content or it won’t generate a box.
  • Case sensitivity of attributes depends on language / i flag in selectors.

On this page