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.
Cheat sheet #6
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.
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 */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.
All the examples in this cheat sheet refer to the page fragment below. Notice that most of it has no classes at all.
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.
| Selector | Matches in the page fragment |
|---|---|
p | All five paragraphs |
h2 | Both h2 headings, “Coffee” and “Cake of the week” |
a | All six links |
li | The three navigation list items |
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.
Separate selectors with a comma so that they share one declaration block. A comma means “or”, so each selector is matched on its own.
Note that if any one selector in the list is invalid, the browser will ignore the entire rule.
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 relationship | Combinator | Syntax |
|---|---|---|
| Ancestor / descendant: any depth | Descendant | a space: nav a |
| Parent / child: one level only | Child | >: nav > ul |
| Siblings: same parent, the next one | Next sibling | +: h2 + p |
| Siblings: same parent, any later one | Later siblings | ~: h2 ~ p |
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.
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.
| Selector | Matches the “Home” link? | Why |
|---|---|---|
li a | Yes | The parent is an ancestor too |
ul a | Yes | A grandparent |
nav a | Yes | An ancestor several levels up |
header a | Yes | An ancestor further up |
body a | Yes | Every visible element is a descendant of body |
main a | No | main is not above this link |
footer a | No | footer 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:
| Selector | Matches in the page fragment |
|---|---|
nav a | “Home”, “Menu” and “Partner” |
main a | “Read more” and “Book a table” |
footer a | The email link |
article p | “Baked in house.” and “Contains nuts.” |
main p | All four paragraphs inside main |
article h2 | “Cake of the week” |
nav ul | The navigation list |
A whole page styled with no classes:
ul in a new div, nav a still works, because nav is still an ancestor.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 > 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.
| Selector | Matches |
|---|---|
nav li | Both items: “Menu” and the nested “Coffee” |
nav > ul > li | Only 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.
+ and ~)Siblings share the same parent, and sibling combinators select an element based on what comes before it.
| Selector | Meaning | Matches in the page fragment |
|---|---|---|
h2 + p | A p immediately after an h2 | “Freshly roasted.” and “Baked in house.” |
h2 ~ p | Any p after an h2, within the same parent | All four paragraphs in main and article |
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.
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 |
| Selector | Matches in the page fragment |
|---|---|
.button | The “Book a table” link |
.warning | The “Contains nuts.” paragraph |
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.
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.
.warning), not their appearance (.red-text). That way, you can change the look later without renaming anything.class="button", not class=".button".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.
<a href="#cake"> (see cheat sheet 2).label to its input.Ids are case-sensitive and must never be shared by two elements. For styling, use type selectors, combinators or a functional class instead.
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.
| Selector | Matches elements… | Example match |
|---|---|---|
[href] | with an href attribute at all | All six links |
[href="menu.html"] | whose value is exactly this | The Menu link |
[href^="https"] | whose value begins with this | The Partner link |
[href$=".pdf"] | whose value ends with this | Links to PDF files |
[href*="example"] | whose value contains this anywhere | The Partner link |
[class~="warning"] | whose space-separated value includes this word | The “Contains nuts.” paragraph |
Attribute selectors are especially useful for form controls (input[type="checkbox"]), and for styling links according to where they point.
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.
| Group | Pseudo-class | Matches |
|---|---|---|
| Links and user action | :link | Links not yet visited |
:visited | Links already visited (browsers limit which properties this can change, mainly colours) | |
:hover | An element under the mouse pointer | |
:focus, :focus-visible | An element with keyboard focus. :focus-visible shows only when a focus ring is needed. | |
:active | An element while it is being pressed | |
| Form state | :checked | Ticked checkboxes and selected radio buttons |
:disabled | Disabled form controls | |
:required | Inputs with the required attribute | |
| Position | :first-child, :last-child | The 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” |
:link, :visited, :hover and :active in that order. The old mnemonic is “LoVe HAte”.:focus-visible a clear style instead of deleting it, and style :hover and :focus-visible together.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-element | Targets |
|---|---|
::before, ::after | Generated content inserted before or after an element’s content. The content property is required. |
::first-line | The first line of text of a block |
::first-letter | The first letter (for drop caps) |
::marker | The bullet or number of a list item |
::placeholder | The placeholder text in an input |
::selection | Text the user has highlighted |
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.
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).
#id counts in the first column..class, [attr] and :hover counts in the second column.p or ::before counts in the third column.* and the combinators themselves add nothing. However, every type selector in a chain still counts, so longer chains score higher.| Selector | Score (ID, class, type) | Note |
|---|---|---|
* | 0, 0, 0 | Lowest possible |
p | 0, 0, 1 | One type |
nav a | 0, 0, 2 | Two types: the combinator itself adds nothing |
header nav ul li a | 0, 0, 5 | Long chains pile up specificity |
.button | 0, 1, 0 | Beats any number of type selectors |
nav a:hover | 0, 1, 2 | A pseudo-class counts like a class |
input[type="email"] | 0, 1, 1 | An attribute selector counts like a class |
#cake | 1, 0, 0 | Beats any number of classes |
:where(.button) | 0, 0, 0 | :where() adds nothing |
style attribute) beat all selectors, and !important overrides almost everything. Avoid both, because they make your CSS hard to maintain.color and font-family, are passed from parents to children unless a selector overrides them.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.
| Type | Syntax | Example | Selects |
|---|---|---|---|
| Type | name | p | All elements of that type |
| List | a, b | h1, h2 | Either selector |
| Descendant | a b | nav a | b anywhere inside a |
| Child | a > b | nav > ul | b directly inside a |
| Next sibling | a + b | h2 + p | b straight after a |
| Later siblings | a ~ b | h2 ~ p | All b after a |
| Universal | * | * | Everything |
| Class | .name | .button | Elements with that class |
| ID | #name | #cake | The one element with that id |
| Attribute | [attr], [attr="v"] | [href^="https"] | By attribute or value |
| Pseudo-class | :state | a:hover | By state or position |
| Pseudo-element | ::part | p::first-line | Part of an element, or generated content |
| Mistake | Fix |
|---|---|
| Putting a class on every element | Use type selectors and descendant combinators. Keep classes for functional jobs. |
Long chains: header nav ul li a | Shorten to nav a |
Using > when a space would do | Use the descendant combinator, unless you need to exclude nested content |
A space where none is wanted: p .warning | Use 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, a | Use 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-text | Name by purpose: .warning |
| The same id on several elements, or ids for styling | Use a class or a structural selector |
Fighting a rule with !important | Lower the specificity of the other rule, or reorder your CSS |
One colon for a pseudo-element: p:first-line | Use p::first-line |
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.