Basic Selectors
Learning Objectives: By the end of this lesson, you will be able to:
- Identify and use the four fundamental CSS selector types
- Target specific HTML elements using appropriate selectors
- Understand the difference between class and ID selectors and when to use each
- Write semantic and maintainable selector names
- Combine multiple selectors effectively in your stylesheets
1. Welcome and Introduction (5 minutes)
Icebreaker Activity
Welcome! Let’s start with a fun identity question: If you could give yourself a CSS class name that represents your personality or skills, what would it be? For example, .coffee-addict, .problem-solver, or .creative-mind?
This exercise helps us think about how CSS selectors work like labels or identifiers that help us target specific elements on a webpage - just like how we use names or descriptions to identify people!
Lesson Overview
- Duration: 60 minutes
- Prerequisites: Basic understanding of HTML elements and CSS syntax
- Materials Needed: Code editor, web browser with developer tools
2. Learning Objectives and Session Outline (5 minutes)
What We’ll Cover Today:
- Selector Fundamentals - What selectors are and why they’re essential for CSS
- Four Core Selector Types - Universal, type, class, and ID selectors
- Selector Strategy - When and how to choose the right selector for different situations
- Hands-on practice - Building a complete webpage using all selector types
- Best practices - Writing maintainable and semantic selector names
Success Criteria:
By the end of this session, you should be able to target any HTML element using the most appropriate selector and write clean, professional CSS code.
3. Foundation Knowledge (15-20 minutes)
Core Concepts
What Are CSS Selectors?
CSS selectors are patterns that tell the browser which HTML elements to style. Think of them as the addressing system of CSS - they help you deliver styling instructions to exactly the right elements on your webpage.
Real-World Analogy: Selectors work like addressing a letter:
- Universal selector (*): “To everyone in the building”
- Type selector (p): “To all the people in apartments”
- Class selector (.residents): “To all residents”
- ID selector (#apartment-5b): “To the person in apartment 5B specifically”
Why This Matters: Good selector strategy is fundamental to maintainable CSS. Poor selector choices lead to code that’s hard to update, debug, and scale.
The Selector-Property-Value Relationship
Every CSS rule follows this pattern:
selector {
property: value;
}
The selector determines WHO gets styled, while properties and values determine HOW they get styled.
Key Terminology
- Selector: The pattern that identifies which elements to style
- Element/Type Selector: Targets all elements of a specific HTML tag
- Class Selector: Targets elements with a specific class attribute
- ID Selector: Targets the unique element with a specific ID attribute
- Universal Selector: Targets all elements on the page
- Specificity: The system that determines which styles take precedence when multiple rules apply
4. Detailed Explanation and Examples (25-30 minutes)
Understanding the Four Fundamental Selectors
Mastering CSS selectors is like learning the vocabulary of CSS. Each selector type serves specific purposes and understanding when to use each one is crucial for writing maintainable, professional CSS.
Universal Selector (*)
The universal selector targets every element on the page. It’s represented by an asterisk (*) and is primarily used for CSS resets or applying base styles.
Syntax:
* {
property: value;
}
When to Use:
- CSS resets (removing default margins/padding)
- Setting universal box-sizing
- Applying base font settings
- Debugging layouts (temporary borders)
Practical Applications:
/* CSS Reset */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* Debug mode - shows all element boundaries */
* {
border: 1px solid red !important;
}
Performance Considerations:
- Use sparingly as it affects every element
- Can impact performance on large pages
- More specific selectors are generally preferred
Type/Element Selector
Type selectors target all elements of a specific HTML tag. They’re the most basic and commonly used selectors.
Syntax:
tagname {
property: value;
}
Common Examples:
h1 { font-size: 2rem; color: #333; }
p { line-height: 1.6; margin-bottom: 1rem; }
img { max-width: 100%; height: auto; }
a { color: #007bff; text-decoration: none; }
When to Use:
- Setting default styles for HTML elements
- Creating consistent typography
- Establishing base styles before adding specific customizations
Best Practices:
- Use for establishing site-wide defaults
- Combine with more specific selectors for refinements
- Keep type selector rules simple and foundational
Class Selector (.classname)
Class selectors target elements with a specific class attribute. They’re the workhorses of CSS and promote reusable, modular styling.
Syntax:
.classname {
property: value;
}
HTML Application:
<div class="card">Content</div>
<section class="card featured">More content</section>
Advantages of Classes:
- Reusable across multiple elements
- Semantic and descriptive naming
- Moderate specificity (not too high, not too low)
- Essential for component-based design
Naming Conventions:
/* Descriptive component names */
.navigation-menu { }
.product-card { }
.call-to-action-button { }
/* BEM methodology example */
.card { }
.card__title { }
.card__content { }
.card--featured { }
/* Utility classes */
.text-center { text-align: center; }
.margin-bottom-large { margin-bottom: 2rem; }
.hidden { display: none; }
ID Selector (#idname)
ID selectors target the unique element with a specific ID attribute. Each ID should appear only once per page.
Syntax:
#idname {
property: value;
}
HTML Application:
<header id="main-header">Site Header</header>
<section id="about-section">About Content</section>
When to Use IDs:
- Unique page sections (header, footer, main navigation)
- JavaScript hooks and form targets
- Anchor links for page navigation
- Specific layout components that appear once
ID vs Class Decision Matrix:
| Use ID When: | Use Class When: |
|---|---|
| Element appears once | Element appears multiple times |
| Unique functionality needed | Styling multiple similar elements |
| JavaScript targeting required | Creating reusable components |
| High specificity needed | Moderate specificity preferred |
Specificity and the Cascade
Understanding how selectors interact is crucial for predictable CSS behavior.
Specificity Hierarchy (from highest to lowest):
- Inline styles (
style="...") - IDs (
#example) - Classes, attributes, and pseudo-classes (
.example,[type="text"],:hover) - Elements and pseudo-elements (
div,::before)
Specificity Example:
/* Specificity: 0,0,0,1 */
p { color: black; }
/* Specificity: 0,0,1,0 */
.intro { color: blue; }
/* Specificity: 0,1,0,0 */
#main-content { color: green; }
/* Specificity: 0,1,1,1 */
#main-content .intro p { color: red; }
Practical Applications
Real-world scenarios where selector choice matters:
Blog Layout Example:
/* Base typography */
h1, h2, h3 { font-family: 'Georgia', serif; }
p { line-height: 1.6; }
/* Layout components */
.article { max-width: 800px; margin: 0 auto; }
.article-header { border-bottom: 1px solid #eee; }
.article-meta { color: #666; font-size: 0.9rem; }
/* Unique elements */
#site-header { background: #333; color: white; }
#main-navigation { position: fixed; top: 0; }
Common Misconceptions
-
Misconception: IDs are always better because they have higher specificity Reality: High specificity can make CSS harder to maintain and override
-
Misconception: You should avoid type selectors in favor of classes Reality: Type selectors are perfect for establishing base styles and defaults
-
Misconception: Class names should describe appearance (
.red-text,.big-font) Reality: Class names should describe purpose or content (.error-message,.page-title)
5. Live Coding Demonstration (20-25 minutes)
Example 1: Basic Selector Implementation
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Selectors Demo</title>
<style>
/* Universal selector - CSS reset */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* Type selectors - base styles */
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
line-height: 1.6;
color: #333;
padding: 20px;
}
h1 {
font-size: 2.5rem;
margin-bottom: 1rem;
color: #2c3e50;
}
h2 {
font-size: 1.8rem;
margin-bottom: 0.8rem;
color: #34495e;
}
p {
margin-bottom: 1rem;
}
/* Class selectors - reusable components */
.container {
max-width: 1200px;
margin: 0 auto;
}
.card {
background: white;
border: 1px solid #ddd;
border-radius: 8px;
padding: 20px;
margin-bottom: 20px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.highlight {
background-color: #fff3cd;
border: 1px solid #ffeaa7;
padding: 15px;
border-radius: 4px;
}
.button {
display: inline-block;
padding: 10px 20px;
background-color: #007bff;
color: white;
text-decoration: none;
border-radius: 4px;
transition: background-color 0.3s ease;
}
.button:hover {
background-color: #0056b3;
}
/* ID selectors - unique elements */
#site-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 40px 0;
text-align: center;
margin-bottom: 40px;
border-radius: 8px;
}
#main-content {
background-color: #f8f9fa;
padding: 30px;
border-radius: 8px;
}
#footer {
margin-top: 40px;
padding: 20px;
background-color: #343a40;
color: white;
text-align: center;
border-radius: 8px;
}
</style>
</head>
<body>
<div class="container">
<header id="site-header">
<h1>CSS Selectors in Action</h1>
<p>Understanding the power of targeting elements</p>
</header>
<main id="main-content">
<h2>Welcome to Our Selector Demo</h2>
<p>This page demonstrates all four basic CSS selector types working together to create a cohesive design.</p>
<div class="card">
<h2>Type Selectors</h2>
<p>All h1, h2, and p elements receive consistent base styling through type selectors.</p>
<div class="highlight">
This highlighted box uses a class selector that can be reused anywhere on the page.
</div>
</div>
<div class="card">
<h2>Class Selectors</h2>
<p>The card layout you're seeing is created with class selectors, making it reusable for multiple content sections.</p>
<a href="#" class="button">Learn More</a>
</div>
<div class="card highlight">
<h2>Combined Classes</h2>
<p>This card combines both the "card" and "highlight" classes, demonstrating how multiple classes can work together.</p>
</div>
</main>
<footer id="footer">
<p>Footer content styled with an ID selector since it appears only once per page.</p>
</footer>
</div>
</body>
</html>
## 6. Hands-On Practice (30-40 minutes)
### Exercise 1: Selector Identification and Implementation (15 minutes)
**Objective:** Practice using all four basic selector types in a single HTML document
**Instructions:**
1. Create an HTML page with various elements
2. Apply styles using each of the four selector types
3. Observe how different selectors affect different elements
4. Use browser developer tools to inspect applied styles
**Starter Code:**
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Selector Practice</title>
<style>
/* Add your CSS here */
/* 1. Use universal selector for CSS reset */
/* 2. Use type selectors for base typography */
/* 3. Use class selectors for components */
/* 4. Use ID selectors for unique elements */
</style>
</head>
<body>
<header id="main-header">
<h1 class="site-title">My Website</h1>
<nav class="navigation">
<a href="#" class="nav-link active">Home</a>
<a href="#" class="nav-link">About</a>
<a href="#" class="nav-link">Contact</a>
</nav>
</header>
<main id="content">
<article class="post">
<h2 class="post-title">My First Blog Post</h2>
<p class="post-meta">Published on <time>January 1, 2025</time></p>
<p>This is the content of my blog post. It should be styled with type selectors for consistent typography.</p>
<p class="highlight">This paragraph has special highlighting.</p>
</article>
<aside class="sidebar">
<h3>About Me</h3>
<p>This is a sidebar with information about the author.</p>
<div class="widget">
<h4>Recent Posts</h4>
<ul>
<li><a href="#">Post 1</a></li>
<li><a href="#">Post 2</a></li>
<li><a href="#">Post 3</a></li>
</ul>
</div>
</aside>
</main>
<footer id="site-footer">
<p>© 2025 My Website. All rights reserved.</p>
</footer>
</body>
</html>
Solution:
/* Universal selector - CSS reset */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* Type selectors - base typography */
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
line-height: 1.6;
color: #333;
}
h1, h2, h3, h4 {
color: #2c3e50;
margin-bottom: 1rem;
}
p {
margin-bottom: 1rem;
}
a {
color: #3498db;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
ul {
list-style-type: disc;
margin-left: 2rem;
}
/* Class selectors - reusable components */
.site-title {
font-size: 2.5rem;
color: white;
}
.navigation {
margin-top: 1rem;
}
.nav-link {
color: #ecf0f1;
margin-right: 2rem;
padding: 0.5rem 1rem;
border-radius: 4px;
transition: background-color 0.3s ease;
}
.nav-link:hover {
background-color: rgba(255,255,255,0.1);
}
.nav-link.active {
background-color: #3498db;
color: white;
}
.post {
background: white;
padding: 2rem;
margin-bottom: 2rem;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
.post-title {
font-size: 1.8rem;
margin-bottom: 0.5rem;
}
.post-meta {
color: #7f8c8d;
font-size: 0.9rem;
margin-bottom: 1.5rem;
}
.highlight {
background-color: #fff3cd;
padding: 1rem;
border-left: 4px solid #ffc107;
margin: 1rem 0;
}
.sidebar {
background: #f8f9fa;
padding: 1.5rem;
border-radius: 8px;
}
.widget {
margin-top: 2rem;
padding-top: 1rem;
border-top: 1px solid #dee2e6;
}
/* ID selectors - unique elements */
#main-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 2rem;
text-align: center;
}
#content {
max-width: 1200px;
margin: 2rem auto;
padding: 0 1rem;
display: grid;
grid-template-columns: 2fr 1fr;
gap: 2rem;
}
#site-footer {
background: #2c3e50;
color: white;
text-align: center;
padding: 2rem;
margin-top: 2rem;
}
Exercise 2: Class vs ID Decision Making (15 minutes)
Objective: Practice deciding when to use classes versus IDs
Challenge: Review the following HTML elements and decide whether they should use a class or ID selector, then explain your reasoning.
<!-- Analyze each element and justify your selector choice -->
<header>Site Header (appears once per page)</header>
<button>Submit Button (multiple submit buttons on page)</button>
<nav>Main Navigation (appears once per page)</nav>
<div>Product Card (multiple products displayed)</div>
<section>About Section (unique content section)</section>
<span>Price Tag (multiple prices shown)</span>
<form>Contact Form (only one contact form)</form>
<div>Error Message (could appear multiple times)</div>
Solution with Reasoning:
| Element | Selector Type | Reasoning |
|---|---|---|
| Site Header | ID (#site-header) |
Appears once per page, unique element |
| Submit Button | Class (.submit-btn) |
Multiple buttons may exist, reusable styling |
| Main Navigation | ID (#main-nav) |
Single navigation per page, unique functionality |
| Product Card | Class (.product-card) |
Multiple products, reusable component |
| About Section | ID (#about-section) |
Unique content section, appears once |
| Price Tag | Class (.price-tag) |
Multiple prices, consistent styling needed |
| Contact Form | ID (#contact-form) |
Single form, may need JavaScript targeting |
| Error Message | Class (.error-message) |
Multiple errors possible, reusable styling |
Exercise 3: Building a Complete Component (10 minutes)
Objective: Create a reusable card component using appropriate selectors
Challenge: Build a news article card that can be used multiple times on a page with the following features:
- Article title and content
- Author information
- Publication date
- Read more button
- Category tag
Requirements:
- Use semantic HTML structure
- Apply appropriate selector types
- Make the component reusable
- Include hover effects
Extension Ideas:
- Add different card variations (featured, small, large)
- Include social sharing buttons
- Add star ratings or other interactive elements
- Create responsive behavior for different screen sizes
7. Common Pitfalls and Troubleshooting (10 minutes)
Frequent Mistakes
-
Problem: Styles not applying to elements Cause: Incorrect selector syntax (missing
.for classes or#for IDs) Solution: Double-check selector syntax and use developer tools to verify -
Problem: Styles being overridden unexpectedly Cause: Specificity conflicts between different selector types Solution: Understand specificity hierarchy and use more specific selectors when needed
-
Problem: Using the same ID on multiple elements Cause: Misunderstanding that IDs must be unique Solution: Use classes for multiple elements, reserve IDs for unique elements
-
Problem: Over-specific selectors making CSS hard to maintain Cause: Chaining too many selectors or using unnecessary specificity Solution: Keep selectors as simple as possible while achieving the desired targeting
Debugging Tips
- Use Browser Developer Tools: Inspect elements to see which styles are applied and why
- Check Selector Syntax: Verify proper use of
.for classes and#for IDs - Understand Specificity: Use specificity calculators to understand which styles take precedence
- Validate HTML: Ensure class and ID attributes are properly formatted in HTML
8. Best Practices and Professional Tips (5 minutes)
Industry Standards
- Semantic Naming: Use descriptive names that indicate purpose, not appearance
/* Good */
.error-message { color: red; }
.primary-button { background: blue; }
/* Avoid */
.red-text { color: red; }
.blue-button { background: blue; }
- Consistent Naming Conventions: Choose a convention and stick to it
/* BEM (Block Element Modifier) */
.card { }
.card__title { }
.card__content { }
.card--featured { }
/* Component-based */
.navigation-menu { }
.navigation-item { }
.navigation-link { }
- Specificity Management: Keep specificity as low as possible while achieving goals
- Reusability: Favor classes over IDs for styling to promote component reuse
Next Steps in Your Learning Journey
- Advanced Selectors: Pseudo-classes, pseudo-elements, attribute selectors
- Combinators: Descendant, child, sibling selectors for complex targeting
- CSS Methodologies: BEM, OOCSS, SMACSS for large-scale CSS organization
- CSS Preprocessors: Sass, Less for enhanced selector capabilities
9. Summary and Review (5 minutes)
Key Takeaways
- Four Fundamental Selectors: Universal (*), type (element), class (.), and ID (#) each serve specific purposes
- Selector Strategy: Choose the right selector based on uniqueness and reusability needs
- Semantic Naming: Use descriptive, purpose-based names for maintainable CSS
Quick Review Questions
- Which selector type would you use for styling all paragraphs on a page?
- When should you use an ID selector instead of a class selector?
- What’s the difference in specificity between
.buttonand#header .button?
Answers:
- Type selector (
p) for base paragraph styling - Use ID when the element appears only once and needs unique targeting
#header .buttonhas higher specificity (0,1,1,0 vs 0,0,1,0)
For Instructors
Teaching Tips
- Visual Demonstrations: Use browser developer tools to show how selectors target elements
- Hands-on Practice: Encourage students to experiment with different selector combinations
- Real-world Examples: Show popular websites and discuss their selector strategies
- Common Mistakes: Address frequent errors like syntax mistakes and specificity conflicts
Assessment Ideas
- Selector Identification Quiz: Given HTML and CSS, identify which elements will be styled
- Practical Exercise: Build a webpage component using appropriate selectors
- Code Review: Have students evaluate and improve existing selector choices
Adaptation Notes
- For Beginners: Focus heavily on the four basic types before introducing combinations
- For Advanced Students: Introduce CSS methodologies like BEM or component-based approaches
- Online Delivery: Use screen sharing for live demonstrations and provide downloadable examples
- Time Management: Core concepts can be covered in 45 minutes, with extended practice taking up to 90 minutes
Example 2: Practical Component Building
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Navigation Component</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
background-color: #f5f5f5;
}
/* Navigation component using class selectors */
.navbar {
background-color: #2c3e50;
padding: 1rem 0;
position: sticky;
top: 0;
z-index: 100;
}
.navbar-container {
max-width: 1200px;
margin: 0 auto;
display: flex;
justify-content: space-between;
align-items: center;
padding: 0 20px;
}
.navbar-brand {
color: white;
font-size: 1.5rem;
font-weight: bold;
text-decoration: none;
}
.navbar-nav {
display: flex;
list-style: none;
gap: 2rem;
}
.navbar-link {
color: #ecf0f1;
text-decoration: none;
padding: 0.5rem 1rem;
border-radius: 4px;
transition: background-color 0.3s ease;
}
.navbar-link:hover {
background-color: #34495e;
color: white;
}
.navbar-link.active {
background-color: #3498db;
color: white;
}
/* Main content area with ID */
#main-content {
padding: 2rem;
max-width: 1200px;
margin: 0 auto;
}
/* Article styling with type selectors */
article {
background: white;
padding: 2rem;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
h1 {
color: #2c3e50;
margin-bottom: 1rem;
}
p {
color: #555;
line-height: 1.8;
margin-bottom: 1rem;
}
</style>
</head>
<body>
<nav class="navbar">
<div class="navbar-container">
<a href="#" class="navbar-brand">SelectorSite</a>
<ul class="navbar-nav">
<li><a href="#" class="navbar-link active">Home</a></li>
<li><a href="#" class="navbar-link">About</a></li>
<li><a href="#" class="navbar-link">Services</a></li>
<li><a href="#" class="navbar-link">Contact</a></li>
</ul>
</div>
</nav>
<main id="main-content">
<article>
<h1>Understanding CSS Selectors</h1>
<p>This navigation component demonstrates practical selector usage in a real-world scenario. The navbar uses class selectors for reusable styling, while the main content area uses an ID selector since it appears once per page.</p>
<p>Notice how type selectors provide consistent typography throughout the article, creating a cohesive reading experience.</p>
</article>
</main>
</body>
</html>
Example 3: Advanced Selector Combinations
/* Targeting specific elements within components */
.card h2 {
color: #2c3e50;
border-bottom: 2px solid #3498db;
padding-bottom: 10px;
}
.card p {
margin-bottom: 15px;
}
.card .button {
margin-top: 20px;
}
/* Multiple class combinations */
.button.primary {
background-color: #3498db;
}
.button.secondary {
background-color: #95a5a6;
}
.button.danger {
background-color: #e74c3c;
}
/* Styling specific instances */
#hero-section .button {
font-size: 1.2rem;
padding: 15px 30px;
}
Debugging Demonstration
Show common errors and how to fix them:
/* Common mistake - forgetting the dot for classes */
card { /* Should be .card */
background: white;
}
/* Common mistake - using # instead of . */
#button { /* Should be .button if it's a class */
color: white;
}
/* Common mistake - overly specific selectors */
body div.container div.row div.col .card h2 {
/* Too specific - hard to override */
}
/* Better approach */
.card-title {
/* Simple, reusable, easy to maintain */
}
/* Universal selector */
* { margin: 0; }
/* Type selector */
h1 { color: navy; }
/* Class selector */
.box { background: #eee; padding: 10px; }
/* ID selector */
#special { color: crimson; font-weight: bold; }
Step-by-Step Explanation
- The universal selector
*removes default margin from all elements. - The type selector
h1colors all<h1>elements navy. - The class selector
.boxgives all elements with classboxa light background and padding. - The ID selector
#specialmakes the paragraph withid="special"crimson and bold.
Best Practices
- Use classes for reusable styles.
- Use IDs for unique elements only.
- Keep selectors as specific as needed, but not more.
- Avoid chaining too many selectors unless necessary (e.g.,
.container .item).
Common Mistakes
- Forgetting to add
classoridattributes in HTML. - Misspelling class or ID names in CSS or HTML.
- Using IDs for multiple elements.
Try It Out!
- Change the class or ID names and see how the styles update.
- Add more elements and apply different selectors.
5. Tasks
- Create an HTML structure with at least two headings, three paragraphs, and two divs.
- Style each using universal, type, class, and ID selectors.
- Try combining classes and IDs on the same element and observe which styles apply (hint: ID selectors are more specific than class selectors).
- Experiment by removing or changing selectors and see the effect.