CSS Selectors — *Where* to Apply Styles
CSS Selectors — *Where* to Apply Styles
🎯 After Reading This Lesson
By the end of this lesson, you will be able to confidently do the following 3 things.
- ▸✅ 5 selector types (element, class, ID, attribute, pseudo) + specificity
- ▸✅ Specificity calculation formula + the danger of !important
- ▸✅ Using :hover / :focus / :nth-child
Keep the learning objectives as a checklist — close the lesson only when you can answer all of them.
What Is a Selector?
The Core Idea
CSS selector = a pattern that specifies which element in HTML to apply a style to. Selecting precisely is the foundation of maintainable CSS.
5 Basic Selector Types
Combinators — Selecting by Relationship
Commonly Used Pseudo-classes
Class vs. ID — When to Use Which
- ▸Class (
.) = reusable across multiple elements. Use this 90% of the time. - ▸ID (
#) = unique on the page. For hooking into JS, anchoring (#section1), or accessibility.
> 💡 Industry convention: Use classes for styling. Reserve IDs for JS hooks or anchor targets only.
Overly Specific Selectors — Maintenance Hell
The longer the selector, the more tightly coupled it is to the HTML structure. Change one line of HTML and all the CSS breaks. A single class name is the safest choice.
BEM Naming Convention — Industry Standard
Prevents conflicts and clarifies intent in complex components. It may feel old-fashioned now that Tailwind and CSS-in-JS exist, but it remains the standard in traditional CSS environments.
Quick Summary
Knowing just the 5 basics (tag, class, ID, attribute, pseudo) and the combinators (child, descendant, sibling) covers 80% of real-world cases. Don't go deeper — keep it simple with a class-first approach.
🤖 Try Asking AI Like This
Once you understand the concepts in this lesson, you can give AI specific instructions. Instead of a vague "fix this," you make vocabulary-driven requests — and that is where token savings begin.
- ▸"Resolve the specificity conflict in this CSS and fix the priority without using !important"
- ▸"Rename these class names following BEM convention"
- ▸"Refactor this nested selector to be flatter (depth 2 or less)"
Why This Saves Tokens
Without the right vocabulary, even after receiving an AI response you have to ask "what does that mean?" all over again. Those follow-up questions eat tokens. Learn the concepts once and conversations wrap up in a single round.