Lesson 12 of 52CSS foundations
Selectors and Specificity
Target exactly the elements you mean, and understand which rule wins when two rules disagree.
A CSS rule has two halves: the selector says which elements to style, and the declarations say how. Most CSS frustration comes from the first half. You write color: red, nothing changes, and the reason is almost always that another rule with a stronger selector is winning. This lesson covers the selectors you will use every day, then the scoring system browsers use to break ties. Once you can score two selectors in your head, "why is my CSS not working?" becomes a question you can answer in seconds.
The basic selectors
Picture a recipe card on a cooking site. It has a title, a list of ingredients and a "Save" button. Here are the four basic ways to point at parts of it.
| Selector | Example | Matches |
|---|---|---|
| Type | p | Every p element |
| Class | .ingredient | Every element with class="ingredient" |
| ID | #main-recipe | The one element with id="main-recipe" |
| Attribute | [type="email"] | Elements whose type attribute is email |
| Universal | * | Every element |
A class is a label you can put on as many elements as you like, and one element can carry several classes separated by spaces: class="card featured". An ID must be unique on the page. In practice, you will style almost everything with classes. IDs are better kept for links (#ingredients) and for JavaScript.
You can also chain selectors with no space to require all of them at once. button.primary means "a button that also has the class primary". And you can group selectors with a comma to share one set of declarations: h1, h2, h3 styles all three.
Preview
Try this: add the class key to "Onion" and watch it turn bold and orange. Then change .ingredient.key to .ingredient .key (with a space) and notice that nothing is bold any more. That space means something completely different, which is the next section.
Combinators: selecting by position
A combinator describes a relationship between two elements. It lets you say "a link, but only inside the navigation" without adding a class to every link.
| Combinator | Example | Matches |
|---|---|---|
| Descendant (space) | nav a | Any a anywhere inside a nav |
Child (>) | ul > li | An li that is a direct child of a ul |
Next sibling (+) | h2 + p | The p immediately after an h2 |
Later siblings (~) | h2 ~ p | Every p after an h2 with the same parent |
To use these, it helps to see the page the way the browser does: as a tree. Every element sits inside a parent, and elements that share a parent are siblings.
In this tree, .card p matches both p.intro and p.note. .card > ul matches the list, but .card > a matches nothing, because the link is a grandchild of the card, not a child. h2 + p matches only p.intro, the paragraph right after the heading.
Pseudo-classes: selecting by state
A pseudo-class starts with one colon and matches an element when it is in a certain state or position. The element does not need any extra class in your HTML; the browser keeps track for you.
:hovermatches while the mouse is over the element.:focus-visiblematches when an element has keyboard focus and the browser decides a focus ring should be shown. Use it for focus styles so keyboard users see where they are, without showing rings on every mouse click.:nth-child(odd),:nth-child(2)or:nth-child(3n)match by position among siblings.:first-childand:last-childare shortcuts.:not(.done)matches elements that do not match the selector inside.:checked,:disabledand:requiredmatch form controls in those states.
Preview
Try this: change odd to even, then to 3n. Click in the preview and press Tab to reach the button, and you will see the blue focus ring. Then remove .done from "Buy flour" and watch it turn bold.
Pseudo-elements: styling parts that are not in the HTML
A pseudo-element starts with two colons and targets a part of an element, or creates a new one. ::before and ::after insert generated content as the first or last child of an element. They only appear if you set the content property, even to an empty string. ::placeholder styles the hint text inside an input, and ::first-line and ::selection style the first line of text and highlighted text.
.price::before { content: "$"; color: #888; }
.required-label::after { content: " *"; color: #b91c1c; }
input::placeholder { color: #6b7280; }Generated content is decoration. Screen readers may or may not read it, so never put information there that a user must have.
Specificity: who wins a tie
When two rules set the same property on the same element, the browser needs a winner. The main tiebreaker is specificity, a score calculated from the selector. Think of it as three columns, compared from left to right like version numbers:
| Column | What counts | Example |
|---|---|---|
| A | ID selectors | #cart |
| B | Classes, attributes, pseudo-classes | .item, [type], :hover |
| C | Type selectors, pseudo-elements | li, ::before |
So #cart .item scores (1, 1, 0) and ul li.item.featured scores (0, 2, 2). The first wins, because one ID beats any number of classes. The universal selector * and combinators add nothing. :not() and :is() take the score of the most specific selector inside them, and :where() always scores zero, which makes it handy for defaults that are easy to override.
Inline styles written in a style attribute beat every selector. And a declaration marked !important jumps above all normal declarations.
The HTML is <p id="intro" class="lead">Hi</p>. What colour is the text?
#intro { color: green; }
p.lead { color: red; }
.lead { color: blue; }Preview
Try this: the text is crimson because .banner p scores (0, 1, 1) and beats .message at (0, 1, 0). Change .message to .banner .message and it turns purple. Then add #sale as the paragraph's id and write #sale { color: orange; } to see an ID win.
Match each selector to its specificity score.
The cascade, in order
Specificity is one step in a longer process called the cascade. When declarations conflict, the browser asks these questions in order and stops at the first one that decides:
- Origin and importance. Your styles beat the browser's built-in defaults, and
!importantdeclarations beat normal ones. - Cascade layers. If you use
@layer, later layers win over earlier ones (covered in Modern CSS). - Specificity. The higher score wins.
- Order of appearance. If everything else ties, the rule that comes last in the CSS wins.
Put the cascade's tiebreakers in the order the browser checks them.
- Tap the steps below in the right order.
Inheritance
Some properties pass down from parent to child automatically. Set color or font-family on body and every paragraph inherits it. Text-related properties generally inherit: color, font-*, line-height, text-align, letter-spacing. Box properties do not: margin, padding, border, background, width. Imagine the mess if every child copied its parent's border.
Inherited values are weak. Any rule that targets the element directly wins over an inherited value, no matter how specific the parent's rule was. If #article { color: navy; } sets the parent and a { color: blue; } targets the link, the link is blue. You can force inheritance with the keyword inherit, for example a { color: inherit; }.
#post { color: navy; }. Its child span has no class, and the stylesheet also contains span { color: gray; }. What colour is the span?Why to avoid !important
!important feels like a fix: the rule finally works. But it wins by opting out of the normal system, and the only way to beat it later is another !important with higher specificity. A codebase that starts using it tends to need more of it, and soon nobody can predict what wins.
Better habits keep you out of trouble. Style with single classes so most selectors score (0, 1, 0). Avoid IDs in CSS. Avoid long chains like .page .sidebar .card ul li a. When something will not change, open the browser devtools, select the element, and look at the Styles panel: overridden declarations are shown crossed out, with the winning rule above them. The few fair uses of !important are utility classes that must always win, such as a .hidden class, and overriding inline styles from a third-party widget you cannot edit.
- selector
- The part of a CSS rule that chooses which elements the declarations apply to.
- combinator
- A symbol between selectors that describes a relationship: space, >, + or ~.
- pseudo-class
- A single-colon keyword like :hover or :nth-child() that matches elements by state or position.
- pseudo-element
- A double-colon keyword like ::before that styles part of an element or generates new content.
- specificity
- A three-column score (IDs, classes, types) that decides which conflicting rule wins.
- cascade
- The ordered process (origin, layers, specificity, source order) that resolves conflicting declarations.
- inheritance
- Some properties, mostly text-related ones, passing from a parent element to its children.