Selectors and Relationships
Target elements with type, class, attribute, and relationship selectors without making rules fragile.
Selectors describe which elements a rule can affect. Classes are reusable hooks, attributes express state or capability, and combinators describe relationships. Prefer the least specific selector that reliably identifies the intended component.
See the core pattern
Read this rule set from the outside in. Identify the inputs, the decision or transformation, and the result before changing it.
.card { border: 1px solid; }
.card > h2 { margin-block-start: 0; }
.card[data-featured="true"] {
border-color: #718817;
}
.card + .card { margin-block-start: 1rem; }Working rules
- Use classes for reusable component styling
- Use child selectors only when the structure is part of the contract
- Reserve IDs for document links and scripting, not routine styling
A common mistake
Long chains such as main .page section div.card h2 are hard to reuse and even harder to override safely.
Guided practice
Write a selector for direct list items inside a navigation list.
- Copy the example into the editable notebook below.
- Change one thing at a time and keep the program or rule valid.
- Explain the result in one sentence without relying on jargon.