CSS ยท Module 13 ยท Lesson 2 of 48

Basic Selectors (Element, Class, ID)

What are CSS Selectors?

Imagine you are a teacher in a classroom filled with students. If you want to give instructions, you have options: 1. Address everyone in a group (e.g., "All students, open your books" โ€” Element selector). 2. Address students wearing red shirts (e.g., "Red shirt group, please stand up" โ€” Class selector). 3. Address a single student by their unique roll number (e.g., "Student ID #01, come here" โ€” ID selector).

CSS selectors work exactly the same way to target HTML nodes:

  • Element Selector: Matches all elements of a certain tag name globally. For example, p targets *every* single paragraph.
  • Class Selector: Matches elements that have a specific class attribute. In CSS, we prefix the class name with a dot .. E.g., .title targets elements with class="title". Multiple elements can share the same class.
  • ID Selector: Matches a single element with a unique id attribute. In CSS, we prefix the ID with a hash #. E.g., #main-heading targets id="main-heading". An ID must be unique on the webpage.
  • Why does it matter?

    If you couldn't select elements precisely, you could never build complex pages. You wouldn't be able to make one specific paragraph stand out with a yellow background, or style the header navigation bar differently from the footer layout. Precise selectors keep your HTML clean while giving you full visual control.

    Syntax Breakdown

  • p { ... } โ€” Targets by HTML tag name. No prefix needed.
  • .highlight { ... } โ€” Targets by class name. Note the leading dot ..
  • #hero { ... } โ€” Targets by ID. Note the leading hash #.
  • p (Tag selector)
    .highlight (Class)
    #hero (ID)

    Common Mistakes

  • Adding the dot/hash inside HTML: Never write class=".title" or id="#hero" inside your HTML code. The prefixes . and # are only used inside CSS files to help the browser distinguish between element names, classes, and IDs.
  • Reusing the same ID: Using the same id value on multiple elements on a single page is invalid HTML. Use classes instead for reusable groups.
  • Quick Reference

  • tag โ€” Targets all elements with this tag.
  • .classname โ€” Targets elements with class="classname".
  • #idname โ€” Targets a single element with id="idname".
  • Your Task
    In the `<style>` tag, target the class `title` (using `.title`) and set its color to `blue`.
    index.html
    Type code above to start the lesson.
    Live Preview