Selectors
Target exactly the right elements
Skills taught: css.selectors, css.pseudo-classes, css.combinators
Basic selectors
/* Element selector — all <p> tags */
p { color: #94a3b8; }
/* Class selector — anything with class="card" */
.card { border-radius: 8px; }
/* ID selector — the element with id="hero" */
#hero { font-size: 3rem; }
/* Universal selector — every element */
* { box-sizing: border-box; }
Tip: Prefer class selectors over ID selectors for styling. IDs are unique — classes are reusable and have lower specificity, making them easier to override.
Attribute selectors
/* Has the attribute at all */
[disabled] { opacity: 0.5; }
/* Exact value match */
[type="submit"] { background: #4fd1c5; }
/* Value contains word */
[class~="active"] { font-weight: bold; }
/* Value starts with */
[href^="https"] { color: green; }
/* Value ends with */
[href$=".pdf"] { color: red; }
Pseudo-classes
Pseudo-classes style elements in a specific state:
/* User interaction states */
a:hover { color: #4fd1c5; } /* mouse over */
a:focus { outline: 2px solid #4fd1c5; } /* keyboard focus */
a:active { opacity: 0.8; } /* being clicked */
/* Form states */
input:disabled { opacity: 0.4; }
input:checked { accent-color: #4fd1c5; }
input:invalid { border-color: red; }
/* Structural */
li:first-child { font-weight: bold; }
li:last-child { border-bottom: none; }
li:nth-child(2) { color: #4fd1c5; }
p:not(.lead) { font-size: 1rem; }
Combinators — relationships between elements
/* Descendant (space) — any a inside nav, at any depth */
nav a { text-decoration: none; }
/* Child (>) — only direct children */
ul > li { list-style: disc; }
/* Adjacent sibling (+) — immediately after */
h2 + p { margin-top: 0; }
/* General sibling (~) — all following siblings */
.active ~ li { opacity: 0.5; }
Grouping selectors
/* Apply same styles to multiple selectors — comma-separated */
h1,
h2,
h3 {
font-family: 'Fira Code', monospace;
font-weight: 700;
}
/* :is() — same thing, but specificity is the highest argument */
:is(h1, h2, h3) { font-family: 'Fira Code', monospace; }
Frequently Asked Questions
When should I use an ID selector vs a class selector?
Use IDs for JavaScript hooks or fragment links (#section). Use classes for all styling — classes are reusable and have lower specificity, making them easier to compose and override.
What is :nth-child() vs :nth-of-type()?
:nth-child(n) counts all siblings regardless of tag. :nth-of-type(n) counts only siblings of the same tag. li:nth-child(2) targets the second child only if it is an li; li:nth-of-type(2) always targets the second li.
What does :not() do?
:not(selector) applies styles to everything that does NOT match the selector. p:not(.lead) targets all paragraphs that don't have the lead class.