Cheat sheet #6

CSS selectors

A cheat sheet for web design students. A selector tells CSS which HTML elements a rule applies to. Learn to select elements by their structure first, using type selectors and combinators, and keep classes for the jobs that only classes can do.

The short version

Style elements by their type and their position in the document. Only add a class when it has a functional job to do, or when structure alone can’t reach the element.

p { } /* type */ nav a { } /* descendant combinator */ .button { } /* functional class */
On this cheat sheet

The anatomy of a CSS rule

Selector, then declarations

A rule has a selector (what to style) and a declaration block in curly braces (how to style it). Each declaration is made up of a property, a colon, a value and a semicolon.

p { /* selector */ color: #14213d; /* property: value; */ font-size: 1.125rem; /* another declaration */ }

All the examples in this cheat sheet refer to the page fragment below. Notice that most of it has no classes at all.

<header> <h1>Hill Café</h1> <nav> <ul> <li><a href="index.html">Home</a></li> <li><a href="menu.html">Menu</a></li> <li><a href="https://example.com/">Partner</a></li> </ul> </nav> </header> <main> <h2>Coffee</h2> <p>Freshly roasted.</p> <p>Open daily.</p> <article> <h2 id="cake">Cake of the week</h2> <p>Baked in house. <a href="cake.html">Read more</a></p> <p class="warning">Contains nuts.</p> </article> <a href="booking.html" class="button">Book a table</a> </main> <footer> <p>Contact <a href="contact.html">hello@hillcafe.example</a></p> </footer>

Type selectors

Select every element of one kind

A type selector is simply the element name, with no dot, hash or other punctuation, and it matches every element of that type on the page. It’s also known as an element selector or a tag selector. Type selectors are the foundation of your stylesheet, because they set the base look of the page.

body { font-family: system-ui, sans-serif; line-height: 1.6; } h1 { font-size: 2.5rem; } h2 { margin-top: 2rem; } p { max-width: 65ch; } a { color: #2a5bd7; }
SelectorMatches in the page fragment
pAll five paragraphs
h2Both h2 headings, “Coffee” and “Cake of the week”
aAll six links
liThe three navigation list items
Dop { color: #14213d; } h1 { font-size: 2.5rem; }
Don’t.p { color: #14213d; } <p> { color: #14213d; } P { color: #14213d; }
Pros
  • It’s short and simple, and there’s nothing to add to your HTML.
  • It rewards semantic HTML, because the element you chose for its meaning also drives its style (see cheat sheet 3 and cheat sheet 4).
  • It has the lowest specificity, so more specific rules can easily override it.
Cons
  • It’s all or nothing, so every element of that type is affected.
  • On its own, it can’t tell a navigation link from a link in a paragraph. Combinators solve that problem (see the next section).

Type selectors are case-insensitive in HTML, so P would also work. However, you should always write element names in lowercase, to match your HTML.

Selector lists: one rule, several selectors

Separate selectors with a comma so that they share one declaration block. A comma means “or”, so each selector is matched on its own.

Doh1, h2, h3 { font-family: Georgia, serif; }
Don’t repeat yourselfh1 { font-family: Georgia, serif; } h2 { font-family: Georgia, serif; } h3 { font-family: Georgia, serif; }

Note that if any one selector in the list is invalid, the browser will ignore the entire rule.

Combinator selectors

Select by where an element sits in the document

A combinator joins two selectors using the relationship between their elements in the document tree. These relationships use the family terms from cheat sheet 3: ancestor, descendant, parent, child and sibling. Combinators let you style the same element type differently in different places, without adding a single class.

Here’s the tree for the page fragment:

Family relationshipCombinatorSyntax
Ancestor / descendant: any depthDescendanta space: nav a
Parent / child: one level onlyChild>: nav > ul
Siblings: same parent, the next oneNext sibling+: h2 + p
Siblings: same parent, any later oneLater siblings~: h2 ~ p

The descendant combinator (a space)

Write two selectors with a space between them. This selects the right-hand element wherever it sits inside the left-hand element, whether it’s a child, a grandchild, a great-grandchild or something deeper. It’s exactly the ancestor / descendant relationship from cheat sheet 3. The left side is the ancestor, and the right side is the descendant you’re styling.

nav a { text-decoration: none; } /* ^ ancestor ^ descendant: the thing being styled */

Read it from right to left. So, nav a means “an a that has a nav somewhere above it”. The target is always the last part of the selector.

Any ancestor will work. Here’s the “Home” link, with its ancestors in the tree:

The li is the parent of the link, and every element to its left is an ancestor. The link is a descendant of all of them.

SelectorMatches the “Home” link?Why
li aYesThe parent is an ancestor too
ul aYesA grandparent
nav aYesAn ancestor several levels up
header aYesAn ancestor further up
body aYesEvery visible element is a descendant of body
main aNomain is not above this link
footer aNofooter is not above this link

Use position to give the same element different jobs. There are six links on the page, and none of them has a class:

nav a { text-decoration: none; font-weight: 600; } /* Home, Menu, Partner */ main a { color: #2a5bd7; } /* Read more, Book a table */ footer a { color: inherit; } /* the email link */
SelectorMatches in the page fragment
nav a“Home”, “Menu” and “Partner”
main a“Read more” and “Book a table”
footer aThe email link
article p“Baked in house.” and “Contains nuts.”
main pAll four paragraphs inside main
article h2“Cake of the week”
nav ulThe navigation list

A whole page styled with no classes:

body { font-family: system-ui, sans-serif; line-height: 1.6; } header h1 { margin: 0; } nav ul { display: flex; gap: 1.5rem; list-style: none; padding: 0; } nav a { text-decoration: none; } main p { max-width: 65ch; } article h2 { font-size: 1.25rem; } footer a { color: inherit; }
Pros
  • There’s no extra markup, so your HTML stays clean and semantic.
  • It’s resilient. If you wrap the ul in a new div, nav a still works, because nav is still an ancestor.
  • Any new links added to the nav are styled automatically.
  • It keeps specificity low and predictable.
Cons
  • It matches at any depth, so it can reach more than you intended, such as the links in a nested menu.
  • It’s tied to the page structure, so if you move an element to a different parent, its styles will change.
  • Long chains become hard to read (see below).

Keep chains short, with two parts, or three at most. For example, nav a is better than header nav ul li a, which says the same thing but breaks the moment the markup changes.

The child combinator (>)

The > symbol only selects direct children. That’s the parent / child relationship, one level down and no deeper. Use it when the descendant combinator would match too much.

<nav> <ul> <li>Menu <ul> <li>Coffee</li> </ul> </li> </ul> </nav>
SelectorMatches
nav liBoth items: “Menu” and the nested “Coffee”
nav > ul > liOnly the top-level “Menu” item. The nested li has a different parent chain.

Use the descendant combinator by default, and only reach for > when you need to exclude nested content. It’s more precise, but it’s also more fragile. For example, nav > a would stop working as soon as a link was wrapped in an li.

The next sibling and subsequent sibling combinators (+ and ~)

Siblings share the same parent, and sibling combinators select an element based on what comes before it.

SelectorMeaningMatches in the page fragment
h2 + pA p immediately after an h2“Freshly roasted.” and “Baked in house.”
h2 ~ pAny p after an h2, within the same parentAll four paragraphs in main and article
h2 + p { font-size: 1.25rem; } /* lead paragraph after a heading */ li + li { margin-top: 0.5rem; } /* space between items, none above the first */

The universal selector

Select everything

The asterisk * matches every element. It adds no specificity, so any other rule will override it. It’s mostly used for site-wide resets, and it can be combined with the combinators above.

*, *::before, *::after { box-sizing: border-box; /* a common reset */ } nav * { margin: 0; } /* every descendant of nav */ main > * + * { margin-top: 1rem; } /* space between the children of main */

Class selectors

Use classes for functional jobs

A class selector is a full stop followed by the class name. It matches every element whose class attribute contains that name, and a single element can have several classes, separated by spaces. Classes are powerful, but on this course they are the exception, not the default, so only reach for one in these situations:

Use a class when…Example
You’re building a reusable component that can appear anywhere.button, .card
You need a utility that does one job.visually-hidden, .text-center
A state is switched on and off, usually by JavaScript.is-open, .is-active
Structure can’t tell two elements apart, such as one of several identical siblings.warning on one paragraph
You need a variation of a component.button.secondary
.button { display: inline-block; padding: 0.5rem 1rem; background: #2a5bd7; color: #fff; } .warning { border-left: 4px solid #a82a22; padding-left: 1rem; } .visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; } .note.highlight { background: #ffe9a8; } /* an element with both classes, no space */ p.warning { } /* a p that also has the class warning */
SelectorMatches in the page fragment
.buttonThe “Book a table” link
.warningThe “Contains nuts.” paragraph

Structure first, class second

Before you add a class, ask yourself whether you can select the element by its type and position. If you can, don’t add one. Putting a class on every element is sometimes called “classitis”. It bloats both the HTML and the CSS, and every class is another name to invent, remember and keep in step.

Do: let the structure do the work<nav> <ul> <li> <a>Home</a> nav ul { } nav li { } nav a { }
Don’t: a class on everything<nav class="main-nav"> <ul class="nav-list"> <li class="nav-item"> <a class="nav-link">Home</a> .nav-list { } .nav-item { } .nav-link { }

Structure and classes work together. Structural rules provide the base style, and a class can override it where needed, because a class has a higher specificity than a chain of type selectors.

main a { color: #2a5bd7; } /* 0,0,2: base style for links in main */ .button { color: #ffffff; } /* 0,1,0: wins on the "Book a table" link */

ID selectors

Select one unique element by its id

An ID selector is a hash followed by the id. Because an id must be unique on the page, an ID selector only ever matches a single element.

#cake { scroll-margin-top: 2rem; } /* matches the "Cake of the week" heading */
Good uses for ids
  • Link targets, such as <a href="#cake"> (see cheat sheet 2).
  • Hooks for JavaScript, and for connecting a form label to its input.
Why not style with them
  • Their specificity is very high, so later rules struggle to override them.
  • They can’t be reused, so you end up repeating your CSS.

Ids are case-sensitive and must never be shared by two elements. For styling, use type selectors, combinators or a functional class instead.

Attribute selectors

Select by an attribute or its value

Put the attribute in square brackets. You can test whether the attribute is present, or compare its value using an operator. This is often the right tool when structure alone can’t reach an element, and it saves you adding a class.

SelectorMatches elements…Example match
[href]with an href attribute at allAll six links
[href="menu.html"]whose value is exactly thisThe Menu link
[href^="https"]whose value begins with thisThe Partner link
[href$=".pdf"]whose value ends with thisLinks to PDF files
[href*="example"]whose value contains this anywhereThe Partner link
[class~="warning"]whose space-separated value includes this wordThe “Contains nuts.” paragraph
nav a[href^="https"] { text-decoration-style: dotted; } /* external links in the nav */ a[href$=".pdf"]::after { content: " (PDF)"; } input[type="email"] { border-color: #2a5bd7; }

Attribute selectors are especially useful for form controls (input[type="checkbox"]), and for styling links according to where they point.

Pseudo-classes

Select by state or position

A pseudo-class starts with a single colon and selects an element when it’s in a particular state (hovered, focused or checked, for example) or position (such as first child). It’s attached to a selector with no space, and it combines naturally with the combinators above.

GroupPseudo-classMatches
Links and user action:linkLinks not yet visited
:visitedLinks already visited (browsers limit which properties this can change, mainly colours)
:hoverAn element under the mouse pointer
:focus, :focus-visibleAn element with keyboard focus. :focus-visible shows only when a focus ring is needed.
:activeAn element while it is being pressed
Form state:checkedTicked checkboxes and selected radio buttons
:disabledDisabled form controls
:requiredInputs with the required attribute
Position:first-child, :last-childThe first or last child of its parent
:nth-child(3)The third child
:nth-child(odd), (even)Every other child, for striping
:nth-child(2n)Every second child (2, 4, 6…)
Logic:not(selector)Elements that do not match
:is(a, b)Matches any in the list, which shortens repeated selectors
:where(a, b)Same as :is(), but adds no specificity
:has(selector)Elements that contain a match: a “parent selector”
nav a:hover, nav a:focus-visible { text-decoration: underline; } nav li:first-child { font-weight: 700; } tr:nth-child(even) { background-color: #e6ecf5; } nav a:not([href^="https"]) { color: #14213d; } /* internal nav links */ li:has(> a) { padding: 0; } /* a li with a link child */ :is(h1, h2, h3) a { color: inherit; } /* links inside any heading */
Do: a single colon with no spacesa:hover li:first-child
Don’t: a space after the element namea :hover li :first-child

Pseudo-elements

Select part of an element, or add generated content

A pseudo-element starts with a double colon. It targets a part of an element, such as its first line, or a virtual element that doesn’t exist in your HTML.

Pseudo-elementTargets
::before, ::afterGenerated content inserted before or after an element’s content. The content property is required.
::first-lineThe first line of text of a block
::first-letterThe first letter (for drop caps)
::markerThe bullet or number of a list item
::placeholderThe placeholder text in an input
::selectionText the user has highlighted
.warning::before { content: "Warning: "; font-weight: 700; } main p::first-letter { font-size: 1.5em; } nav li::marker { color: #2a5bd7; } input::placeholder { color: #4b5a75; }
Pseudo-element: two colonsp::first-line div::after
Pseudo-element: one colonp:first-line div:after

Browsers still understand the single-colon syntax, but it’s best practice to use two colons, so that pseudo-elements are easy to tell apart from pseudo-classes.

Only use generated content for decoration. Text added with content isn’t reliably available to everyone, and it can’t be selected, so any real information belongs in your HTML.

Specificity and the cascade

When two rules clash, the more specific selector wins

Several rules can target the same element, and when they do, the browser picks the winner by specificity. You can score specificity as three counts, compared from left to right: (IDs, classes, types).

SelectorScore (ID, class, type)Note
*0, 0, 0Lowest possible
p0, 0, 1One type
nav a0, 0, 2Two types: the combinator itself adds nothing
header nav ul li a0, 0, 5Long chains pile up specificity
.button0, 1, 0Beats any number of type selectors
nav a:hover0, 1, 2A pseudo-class counts like a class
input[type="email"]0, 1, 1An attribute selector counts like a class
#cake1, 0, 0Beats any number of classes
:where(.button)0, 0, 0:where() adds nothing

That’s why this approach works. Type selectors and short descendant chains give your base styles a low, flat specificity, and a single functional class is always enough to override them, with no need for IDs or !important.

Quick reference

TypeSyntaxExampleSelects
TypenamepAll elements of that type
Lista, bh1, h2Either selector
Descendanta bnav ab anywhere inside a
Childa > bnav > ulb directly inside a
Next siblinga + bh2 + pb straight after a
Later siblingsa ~ bh2 ~ pAll b after a
Universal**Everything
Class.name.buttonElements with that class
ID#name#cakeThe one element with that id
Attribute[attr], [attr="v"][href^="https"]By attribute or value
Pseudo-class:statea:hoverBy state or position
Pseudo-element::partp::first-linePart of an element, or generated content

Common mistakes

MistakeFix
Putting a class on every elementUse type selectors and descendant combinators. Keep classes for functional jobs.
Long chains: header nav ul li aShorten to nav a
Using > when a space would doUse the descendant combinator, unless you need to exclude nested content
A space where none is wanted: p .warningUse p.warning for a paragraph that has the class. The first selects a .warning inside a paragraph.
A comma where a space is wanted: nav, aUse nav a. A comma selects both separately.
Forgetting the . or #: button { }Write .button. Without the dot, CSS looks for a <button> element.
Classes named for looks: .red-textName by purpose: .warning
The same id on several elements, or ids for stylingUse a class or a structural selector
Fighting a rule with !importantLower the specificity of the other rule, or reorder your CSS
One colon for a pseudo-element: p:first-lineUse p::first-line

Check before you upload

Learn more

Tip: in your browser’s dev tools, inspect an element and look at the Styles panel. It lists every matching rule in order of specificity, with any overridden declarations crossed out.