CSS

Lesson 2: CSS Selectors & Targeting

Duration: 60 minutes | Difficulty: Beginner | Prerequisites: Lesson 1 completed

📋 Learning Objectives

By the end of this lesson, you will be able to:

🎯 Key Concepts

CSS Selectors Overview

Selectors are patterns that tell CSS which HTML elements to style. They are the bridge between your HTML structure and CSS styling rules.

🔧 Types of CSS Selectors

1. Universal Selector

Selects all elements on the page.

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

2. Element Selector

Targets all elements of a specific HTML tag.

h1 { 
    color: navy; 
    font-size: 2rem; 
}

p { 
    line-height: 1.6; 
    margin-bottom: 1rem; 
}

a { 
    text-decoration: none; 
    color: #0066cc; 
}

3. Class Selector

Targets elements with a specific class attribute (prefixed with .).

.highlight { 
    background-color: #fff3cd; 
    padding: 0.5rem; 
    border-left: 4px solid #ffc107; 
}

.btn { 
    display: inline-block; 
    padding: 0.75rem 1.5rem; 
    border: none; 
    border-radius: 4px; 
    cursor: pointer; 
}

.btn-primary { 
    background-color: #007bff; 
    color: white; 
}

4. ID Selector

Targets a single element with a specific ID (prefixed with #).

#header { 
    background-color: #333; 
    color: white; 
    padding: 2rem 0; 
}

#navigation { 
    position: sticky; 
    top: 0; 
    z-index: 100; 
}

5. Descendant Selector

Targets elements that are descendants of another element (separated by space).

/* All <a> tags inside <nav> elements */
nav a { 
    color: white; 
    padding: 0.5rem 1rem; 
}

/* All <p> tags inside elements with class 'article' */
.article p { 
    text-align: justify; 
    color: #555; 
}

/* Nested example */
.sidebar .widget h3 { 
    font-size: 1.2rem; 
    margin-bottom: 0.5rem; 
}

6. Child Selector

Targets direct children only (uses >).

/* Only direct <li> children of <ul> */
ul > li { 
    list-style-type: disc; 
    margin-left: 1rem; 
}

/* Direct paragraphs inside .content, not nested ones */
.content > p { 
    font-size: 1.1rem; 
}

7. Attribute Selectors

Target elements based on their attributes.

/* All input elements with type="text" */
input[type="text"] { 
    border: 2px solid #ddd; 
    padding: 0.5rem; 
}

/* All links with target="_blank" */
a[target="_blank"] { 
    color: #e74c3c; 
}

/* Elements with class containing "card" */
[class*="card"] { 
    border-radius: 8px; 
    box-shadow: 0 2px 4px rgba(0,0,0,0.1); 
}

/* Links that start with "https://" */
a[href^="https://"] { 
    padding-left: 20px; 
    background: url('secure-icon.png') no-repeat left center; 
}

8. Pseudo-Classes

Target elements in specific states or positions.

/* Hover effect */
a:hover { 
    color: #ff6b6b; 
    text-decoration: underline; 
}

/* First child */
.menu li:first-child { 
    border-top: none; 
}

/* Last child */
.menu li:last-child { 
    border-bottom: none; 
}

/* Nth child (even rows) */
tr:nth-child(even) { 
    background-color: #f8f9fa; 
}

/* Focus state for form inputs */
input:focus { 
    outline: none; 
    border-color: #007bff; 
    box-shadow: 0 0 0 3px rgba(0,123,255,0.25); 
}

/* Visited links */
a:visited { 
    color: #6f42c1; 
}

9. Pseudo-Elements

Style specific parts of elements.

/* First letter of paragraphs */
p::first-letter { 
    font-size: 3rem; 
    float: left; 
    line-height: 1; 
    margin-right: 0.1rem; 
}

/* Add content before/after elements */
.quote::before { 
    content: '"'; 
    font-size: 2rem; 
    color: #999; 
}

.quote::after { 
    content: '"'; 
    font-size: 2rem; 
    color: #999; 
}

⚖️ CSS Specificity

Specificity determines which CSS rule applies when multiple rules target the same element.

Specificity Calculation:

  1. Inline styles: 1000 points
  2. IDs: 100 points each
  3. Classes, attributes, pseudo-classes: 10 points each
  4. Elements and pseudo-elements: 1 point each

Examples:

/* Specificity: 1 (one element) */
p { color: black; }

/* Specificity: 10 (one class) */
.text { color: blue; }

/* Specificity: 100 (one ID) */
#main { color: red; }

/* Specificity: 111 (1 ID + 1 class + 1 element) */
#main .text p { color: green; }

/* Specificity: 21 (2 classes + 1 element) */
.sidebar .widget p { color: purple; }

🛠️ Hands-On Exercises

Exercise 1: Basic Selectors

Create HTML and style it using different selector types:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Selectors Practice</title>
    <link rel="stylesheet" href="selectors.css">
</head>
<body>
    <header id="main-header">
        <h1>My Website</h1>
        <nav class="navigation">
            <ul>
                <li><a href="#home">Home</a></li>
                <li><a href="#about">About</a></li>
                <li><a href="#contact">Contact</a></li>
            </ul>
        </nav>
    </header>
    
    <main class="content">
        <article class="post featured">
            <h2>Featured Article</h2>
            <p class="intro">This is the introduction paragraph.</p>
            <p>This is a regular paragraph with <a href="https://example.com" target="_blank">an external link</a>.</p>
        </article>
        
        <aside class="sidebar">
            <div class="widget">
                <h3>Recent Posts</h3>
                <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>
</body>
</html>

Your Task: Write CSS to:

  1. Style the header with a dark background and white text
  2. Make navigation links inline with hover effects
  3. Give the featured article a border and different background
  4. Style external links differently from internal links
  5. Add alternating colors to sidebar list items

Exercise 2: Specificity Challenge

Determine which color will be applied to each element:

p { color: black; }
.text { color: blue; }
#content p { color: red; }
.container .text { color: green; }
#content .container p { color: purple; }
<div id="content">
    <div class="container">
        <p class="text">What color am I?</p>
    </div>
</div>

🚨 Common Pitfalls

  1. Overusing IDs: Use classes for styling, IDs for JavaScript targeting
  2. High specificity: Avoid overly specific selectors that are hard to override
  3. Missing spaces: div.class vs div .class have different meanings
  4. Case sensitivity: Class and ID names are case-sensitive

🔍 Best Practices

  1. Use classes for styling: More flexible and reusable than IDs
  2. Keep specificity low: Easier to maintain and override when needed
  3. Be semantic: Use meaningful class names that describe purpose
  4. Group related selectors: Organize CSS logically
  5. Use descendant selectors wisely: Don’t nest too deeply

📝 Assessment

Quick Quiz

  1. What’s the difference between .class p and .class > p?
  2. Which has higher specificity: #nav .menu or .header .nav?
  3. How do you select all input elements with type=”email”?
  4. What pseudo-class targets the first child element?

Practice Tasks

  1. Create a navigation menu with hover effects
  2. Style a table with alternating row colors
  3. Create a card component using class selectors
  4. Practice combining different selector types

🔗 What’s Next?

In Lesson 3, we’ll explore Typography & Colors, learning how to work with fonts, text properties, color systems, and create beautiful readable text designs.


Master these selectors as they form the foundation for all CSS styling. Practice with the example files and experiment with different combinations.