CSS Basics
Selectors
Master CSS selectors, covering type, class, ID, attribute selectors, pseudo-classes, pseudo-elements, and the rules of CSS specificity.
1. Learning Objectives
In this lesson, you will master targeting HTML elements with CSS. By the end of this topic, you will be able to:
- Identify and use standard CSS selectors (type, class, and ID).
- Target elements based on attributes and relational sibling/child positions.
- Apply interactive states using pseudo-classes (like
:hoverand:focus). - Style parts of elements using pseudo-elements (like
::beforeand::after). - Calculate and resolve CSS specificity conflicts.
2. Overview
CSS selectors define which HTML elements style rules apply to. Selectors range from basic element type targets to complex attribute patterns, pseudo-states, and relational matches. When multiple selectors target the same element, the browser resolves conflicts using the rules of **CSS Specificity**.
3. Why This Topic Matters
Understanding how selectors target elements prevents layout and debugging issues:
- Specificity Wars: If you do not understand specificity calculations, you might find yourself adding
!importantdeclarations to force styles to apply. This makes stylesheet debugging difficult. - Interactive Access: Failing to style elements on
:focusprevents keyboard navigation users from identifying active interactive components.
4. Real-World Analogy
Think of CSS selectors like **mailing invites to guests**:
- Type Selector (element): Sending an invite to everyone who has a certain job title (e.g. "All software engineers").
- Class Selector (.class): Inviting everyone who belongs to a specific club (e.g. members of the "Tennis Club" class).
- ID Selector (#id): Sending a specific, personal invite to a single home address (e.g. "John Smith").
- Pseudo-class (:hover): Giving a gift only to guests who are actively standing at the registration desk (active state).
5. Core Concepts
CSS specificity is calculated using a four-category score weight:
| Selector Tier | Weight Score | Target Examples |
|---|---|---|
| Inline Style | 1000 points | style="color: red;" |
| ID Selector | 100 points | #header-title |
| Class, Attribute, Pseudo-class | 10 points | .btn, [type="email"], :hover |
| Type Selector, Pseudo-element | 1 point | h1, div, ::before |
6. Syntax & API Reference
Here is a summary of standard selector options:
7. Visual Diagram
This diagram displays how the browser calculates specificity points to resolve conflicts:
8. Live Example — Full Working Code
A sample showing how different selectors and specificity rules override each other:
9. Interactive Playground
Try It Yourself Challenges:
- Add a class selector rule targeting
.highlight-textwith an!importantflag on the color property. Observe which color rule applies to the paragraph. - Test what happens when two selectors have the exact same specificity score. (Hint: The cascade rule applies).
10. Common Mistakes
| Mistake | Why it happens | Wrong | Correct |
|---|---|---|---|
| Styling with ID selectors | Using ID selectors for standard components, which creates specificity issues. | #main-button { padding: 8px; } |
.btn-main { padding: 8px; } |
| Overusing !important | Using `!important` to solve specificity conflicts, making the CSS hard to override. | color: blue !important; |
Structure selectors to use proper specificity scores instead. |
11. Best Practices
- Keep specificity low: Use class selectors for component styling. Keeping specificity scores low makes it easier to override styles later in the stylesheet.
- Avoid styling with ID selectors: ID selectors have high specificity, making them difficult to override without using inline styles or
!importanttags. - Always style :focus states: Provide clear
:focusstyles for interactive elements (links, buttons, inputs) to support keyboard navigation. - Use double colons for pseudo-elements: Use double colons for pseudo-elements (e.g.
::after) and single colons for pseudo-classes (e.g.:hover) to match modern CSS standards.
12. Browser Compatibility
| Feature | Chrome | Firefox | Safari | Edge |
|---|---|---|---|---|
| Standard pseudo-classes (:hover, :focus) | Supported | Supported | Supported | Supported |
| Pseudo-elements (::before, ::after) | Supported | Supported | Supported | Supported |
13. Interview Questions
🟢 Q1: Calculate the specificity score for the selector `body main .card button:hover`.
Answer: The specificity score is **22**.
- Class & pseudo-class: 2 (.card, :hover) = 20 points
- Elements: 2 (body, main, button) = 2 points
- Total specificity weight: 22 points (written as 0,0,2,2).
14. Debugging Exercise
Explain why the text color of the span in this markup is red instead of blue, and fix the CSS configuration:
Diagnosis: The selector #sidebar span has a specificity of **101** (1 ID + 1 element), which overrides .nav-label, which has a specificity of **10** (1 class). To make the class selector rule apply, we must increase its specificity or structure the selectors correctly.
Fixed CSS:
15. Practice Exercises
Exercise 1: Selector Priority Grid
Build an HTML structure containing three nested divs. Write CSS rules using type, class, and ID selectors targeting the innermost div. Observe how the styled colors override each other to verify specificity calculations.
16. Scenario-Based Challenge
The Style Refactoring Specificity Challenge:
Your product's CSS files contain 5,000 lines of CSS with over 150 instances of the !important flag. Developers are complaining that styling updates do not apply, forcing them to use even more !important flags. Propose an implementation plan to clean up specificity conflicts by refactoring ID and element selectors into reusable class patterns.
17. Quick Quiz
Q1: Which selector has the highest specificity score?
A) .card .title p
B) #header-banner
C) div[class="nav"]
Answer: B — ID selectors (#header-banner) yield a high specificity score of 100 points.
18. Summary & Key Takeaways
- • Specificity is calculated based on: Inline Styles, IDs, Classes/Attributes, and Elements.
- • When specificity scores are equal, the last rule declared in the stylesheet wins.
19. Cheat Sheet
| Selector | Specificity Weight |
|---|---|
.class-name |
10 points |