Skip to main content
CodeOath

Chapter 1 · About 12 minFree

Selectors, pseudo-classes and custom properties

Learn which elements a selector really matches, how focus rings and generated content behave, and why a custom property can hold a wrong value with no error.

Published by Hem Mankad, founder of CodeOath and a software engineer for more than eight years. Prepared with AI assistance.

Kelpwick's timetable page

This track builds the front end of Kelpwick Ferries, an invented operator with two small boats that cross between Marrow Quay and Skerry Isle. Every price, time and name in the story is made up. The first page is the timetable: an intro paragraph, then one card for each sailing with a heading, a note, a price and sometimes a badge such as "Delayed" or "Full".

The chapter assumes you know the box model and how the cascade picks a winner. It is about the other half of writing CSS: saying which elements a rule is for, and keeping values in one place. Every number below was measured. A fixture page with the exact markup and styles was opened in Chrome 152 in a 1280 by 800 window, match counts came from querySelectorAll() and values from getComputedStyle(). Where a result depends on a real mouse or keyboard, the page was driven with a real click and a real Tab key.

Combinators describe where an element sits

A plain selector names a kind of element. A combinator adds a position: a descendant (a space), a direct child (>), the very next sibling (+) or any later sibling (~). The descendant combinator is the one you will type most, and the easiest to make too wide.

The timetable page needs a muted, smaller intro. Someone writes:

.timetable-page p { color: rgb(102, 102, 102); font-size: 14px; }

The rule matches 5 paragraphs, not 1. It reaches the intro and also the four sailing notes, which live deeper inside the same page. Measured, the note on the first sailing is rgb(102, 102, 102) at 14px, dimmed by a rule that was never meant for it. Nothing reports an error; a descendant selector simply goes as far down as it can. Say what you mean instead:

.timetable-page > .intro p { color: rgb(102, 102, 102); font-size: 14px; }

That version matches exactly 1 paragraph, and the note keeps its normal black.

The sibling combinators depend on order inside one parent. Each sailing card holds, in order, a heading, a note, a price and an optional badge. h3 + .note matches 4 elements, one per card, because the note really is the heading's next sibling. h3 + .price matches 0, because the note sits in between and + only looks at the very next element. h3 ~ .badge matches 2, the two cards that have a badge, since ~ accepts any later sibling. .price + .badge also matches 2 here, which is a stricter way to say the same thing for this markup.

A working habit: choose > whenever the rule is about direct children, and keep the descendant space for cases where depth truly does not matter. Selectors that stop at the right depth are the ones that survive a redesign.

Attribute selectors read the markup

An attribute selector matches on what is written in the HTML, so you do not have to invent and keep in sync a class for something the markup already says. A test list of five links, two spans with a data-flag word list and three paragraphs with a lang attribute gave these counts:

a[href^="https://"]     /* starts with: 2 links */
a[href$=".pdf"]         /* ends with: 1 link */
a[href$=".pdf" i]       /* ends with, ignoring case: 2 links */
a[href*="timetable"]    /* contains: 2 links */
[data-flag~="bike"]     /* one word in a space-separated list: 1 element */
[data-flag*="bike"]     /* contains the letters: 2 elements */
[lang|="en"]            /* "en" or "en-" and more: 2 paragraphs */
[lang^="en"]            /* starts with the letters: 3 paragraphs */

Two of the pairs show why the operator matters. The page has one PDF link written winter.pdf and one written SUMMER.PDF. Plain $= found only the first; the i flag found both. A span marked data-flag="bikeshare" is caught by *= but not by ~=, because ~= compares whole words. Likewise [lang^="en"] also caught lang="english", which is not a language code, while |= stopped at "en" and "en-GB".

The best use of an attribute selector is state that script already stores. A card marked data-status="delayed" can be styled by .sailing[data-status="delayed"], and the same attribute is what a script reads to decide whether to show a banner. One source of truth cannot disagree with itself, which a class kept in sync by hand can.

Pseudo-classes match state and position

A pseudo-class, written with one colon, matches an element by what is true about it at the moment: hovered, focused, the third child, has a badge inside.

Hover and focus. Hover was measured with the pointer resting on a button: its background changed to rgb(250, 240, 200) through :hover. Focus is subtler. The same page logs :focus-visible on each event. In Chrome, after a mouse click on a button, the button matched :focus but not :focus-visible; not every browser focuses a button on a click, and only Chrome was tested. After Tab moved focus to the next button, the new button matched both. Clicking into a text input matched both. That behaviour is what makes :focus-visible the right place for a focus ring: keyboard users and text fields get it, and a mouse click on a button does not paint an outline.

.button:focus-visible { outline: 3px solid rgb(0, 0, 255); outline-offset: 2px; }

Position. :nth-child(an+b) counts siblings from 1. On a list of eight weekday rows, the selectors matched:

SelectorRows matched
2n or even2, 4, 6, 8
2n+1 or odd1, 3, 5, 7
33
-n+31, 2, 3
n+66, 7, 8
3n+11, 4, 7

li:nth-child(n+3):nth-child(-n+5) gave 3, 4 and 5, and :nth-last-child(2) gave 7, counting from the end. Remember that n starts at 0 and the element numbers start at 1; that is why -n+3 stops at 3.

:nth-child counts every kind of sibling. :nth-of-type counts only elements of the same tag. In a container that holds, in order, a heading, a paragraph, a paragraph, a heading and a paragraph, p:nth-child(2) matched the first paragraph, because it is the second child, while p:nth-of-type(2) matched the second paragraph. If the markup might gain a heading later, :nth-of-type is the steadier choice.

Negation and parent selection. :not() matches elements that fail a test: .sailing:not(.route-north) matched 3 of the 4 cards. :has() goes the other way up the tree and selects an element based on what it contains:

.sailing:has(.badge) { outline: 2px solid rgb(200, 0, 0); }

It matched the 2 cards with a badge, and the computed outline style was solid on those two and none on the other two. Before :has(), styling a parent by its children needed script. It also reads form state: with one empty required input and one filled one, input:invalid matched only the empty field and form:has(input:invalid) matched the form. :has() needs a current browser, and the chapter was measured in Chrome 152.

Form state. The booking form that comes later in the track is full of state, and the browser tracks most of it for you. On five inputs, :placeholder-shown matched 1, the empty one, and not the field that already held typed text. :disabled matched 1 and :enabled matched the other 4. :checked matched 1 of the two checkboxes. Selecting by state like this removes a whole family of classes that script would otherwise have to add and remove, and then forget to remove.

Pseudo-elements are pieces of an element

A pseudo-element, with two colons, does not select an element. It styles a part of one, or creates a part that has no tag in the markup. ::before and ::after insert generated content, and they do nothing until content is set:

.tagged::before { content: "\2693  "; }
.timed::after   { content: attr(data-time); margin-left: 8px; }

On a paragraph with data-time="08:15" the computed content of ::before was the anchor symbol with a space, and of ::after it was "08:15". The paragraph's own textContent stayed "Marrow Quay", and so did innerText. The generated text is drawn but is not part of the document's text. A selector cannot reach it either: querySelectorAll("p::before") matched 0. A second paragraph with only .plain::before { color: red } and no content had a computed content of none, so nothing was drawn at all, despite the red colour; the colour was set, but there was no box to wear it.

Some pseudo-elements style a part that already exists but has no element of its own. ::marker is the bullet or number of a list item, and ::placeholder is the hint text in an empty field:

#marks li::marker { color: rgb(9, 9, 9); }
#pf::placeholder  { color: rgb(120, 120, 120); }

Both took effect: getComputedStyle(item, "::marker").color returned rgb(9, 9, 9) and the placeholder reported rgb(120, 120, 120). As with ::before, a selector query for li::marker matched 0 elements, so these can be styled but never selected, scripted or clicked.

This is the rule for what goes inside content: decoration only. How a screen reader treats generated text differs between browsers and readers, and this chapter did not test any reader. Anything a visitor must be able to read, such as a delay warning, belongs in the markup.

Custom properties are values the browser keeps

A custom property is a name starting with two dashes. Unlike a variable in a preprocessor, it is not replaced before the page loads. The browser keeps it, resolves it on the element that uses it, and re-resolves it when anything changes. The sailing cards use two:

:root { --brand: #0b5d6b; --gap: 12px; }
.sailing { border-left: 4px solid var(--brand); padding: var(--gap); }
.route-north { --brand: #7a3d00; }

Custom properties inherit. A normal sailing's border measured rgb(11, 93, 107), which is #0b5d6b. A card with the route-north class measured rgb(122, 61, 0), which is #7a3d00, and a span inside that card reported --brand as #7a3d00 too, passed down from its parent. Redefining a variable on one element re-themes everything below it without touching the card's own rule.

Because the value lives in the browser, script can change it. Setting --gap on the root to 30px with document.documentElement.style.setProperty("--gap", "30px") moved the card padding from 12 to 30 pixels, and removeProperty returned it to 12. An element that defines its own copy ignores the change. A test box with --gap: 10px and padding: calc(var(--gap) * 2) measured 20 pixels both before and after, because its nearest --gap was its own.

Custom properties also follow the cascade like any other property, and the rules on specificity and order apply to them unchanged. Three boxes shared a class that set --x: two; one also had an id rule setting --x: one, and another an id rule setting --x: three. The boxes reported "one", "three" and, for the box with the class alone, "two". Names are case sensitive: one element given both --Brand: upper and --brand: lower held two separate values, "upper" and "lower", so a capital letter typed by mistake creates a second variable and the first keeps its old value.

A variable can hold a bare number and take its unit where it is used. With --n: 12 and width: calc(var(--n) * 1px) the measured width was 12 pixels, and the same --n can feed a second rule that needs a different unit. To switch inheritance off for one subtree, set the variable to initial: inside a parent where --x was "kept", a child with --x: initial read an empty string, while its sibling still read "kept". That is the initial value of a custom property, a special invalid value that reads as an empty string, and var() uses its fallback there: with color: var(--x, rgb(10, 20, 30)) the colour was rgb(10, 20, 30). A variable you set to nothing yourself, --x:;, is a real empty value that reads as an empty string too, and there the fallback does not apply: the colour stayed rgb(0, 0, 0).

var() takes a fallback after a comma, used when the name is missing:

.fb { color: var(--missing, rgb(10, 20, 30)); }

That element measured rgb(10, 20, 30). Without a fallback, color: var(--missing) has nothing to use, and the declaration acts as if it were never set; the colour inherited from the parent, rgb(0, 0, 0).

The trap is a value that exists but does not fit. With --size: red; and width: var(--size), the browser accepts the rule when it parses the file, because it cannot know yet what the variable holds. It finds the problem only when it computes the width, and then the declaration is dropped. The measured width was 1233 pixels, which is auto in this window: the full width of the container. No error appears anywhere. When a property that uses var() seems to be ignored, read the variable's value in the developer tools before you suspect the rule.

Mistakes that recur

  • A descendant selector cast wider than intended. .page p styled five paragraphs when one was meant; use > or a class.
  • Mixing up child and type counting. :nth-child(2) is the second child of any kind; :nth-of-type(2) is the second of that tag.
  • Using :focus for the ring. A mouse click on a button then paints an outline; :focus-visible is the one that follows keyboard use.
  • Putting meaning in content. Generated text is not in the document text; keep delay warnings and prices in the markup.
  • Trusting a variable that holds the wrong kind of value. A colour in a width quietly turns the width into auto; check the computed value.
  • Typing a variable name with the wrong case. --Brand and --brand are two variables; the one you forgot to update keeps its old value.
  • Redefining a variable in one place and expecting it everywhere. Custom properties follow inheritance, so a copy on a card only reaches that card's descendants.

Carry forward: a combinator picks elements by position, an attribute selector by what the markup says, a pseudo-class by state or place, and a pseudo-element styles a part that is not in the text. Custom properties give values one home and let a subtree or a script change them. The next chapter turns to positioning, stacking and units.

Coming: the guide answers questions in a later release.