Skip to main content
April 1, 2026Dan Rodney/7 min read

CSS Class Selectors: Free HTML & CSS Tutorial

Master CSS Class Selectors and Element Targeting

Core Concepts You'll Learn

Class Attributes

Learn how to add class attributes to HTML elements to create unique identifiers for styling purposes.

CSS Class Selectors

Master the dot notation syntax to target specific elements with custom styles that override default tag selectors.

Span Tag Implementation

Discover how to use span tags to wrap inline content and apply targeted styling to specific text portions.

Topics Covered in This HTML & CSS Tutorial:

The Class Attribute, CSS Class Selectors, the Span Tag, CSS Opacity

Exercise Preview

css classes

Prerequisites Check

This exercise builds on previous lessons about CSS tag selectors. Make sure you understand how basic tag selectors work before proceeding with class-based targeting.

Exercise Overview

In the previous exercise, you learned that CSS tag selectors provide an efficient way to apply consistent styling across all instances of a specific tag. However, real-world web development demands greater flexibility. What happens when you need one paragraph to stand out from the rest, or when certain elements require unique styling while maintaining overall design consistency? In this exercise, you'll master the powerful class selector — a fundamental CSS technique that allows you to create targeted style overrides wherever needed, giving you precise control over your design while maintaining clean, semantic markup.

  1. If you completed the previous exercise, index.html should still be open in your code editor, and you can skip the following sidebar. If you closed index.html, re-open it now from the News website folder. We strongly recommend completing the previous exercises (1C–1D) before proceeding, as they establish the foundational knowledge you'll build upon here. If you haven't finished those exercises, follow the setup instructions in the sidebar below.

If You Did Not Do the Previous Exercises (1C–1D)

  1. Close any files you may have open in your editor.
  2. In your code editor, open index-ready-for-classes.html from the News website folder.
  3. Perform a File > Save As and save the file as index.html, replacing the older version in your folder.
  • Preview the file in your browser to establish a baseline view of the current styling. This will help you clearly see the changes as you implement class-based styling.

    TIP: If you're using Visual Studio Code with the open in browser extension installed, press Option–B (Mac) or ALT–B (Windows) to instantly open your HTML file in your default browser. This keyboard shortcut will save you significant time during development.

  • Quick Setup for New Learners

    1

    Open Starting File

    Close any open files and locate index-ready-for-classes.html in your News website folder using your code editor.

    2

    Save As New Version

    Use File > Save As to save the file as index.html, replacing any older version in your project folder.

    3

    Preview in Browser

    Open the HTML file in your browser to see the current appearance before making changes.

    Browser Shortcut

    Visual Studio Code users with the open in browser extension can use Option-B (Mac) or ALT-B (Windows) to quickly open HTML files in the default browser.

    Class Selectors: Making Exceptions to the Defaults

    Class selectors represent one of CSS's most powerful features, enabling you to create targeted styling exceptions without disrupting your base design system. Think of classes as custom labels you attach to HTML elements — these labels allow you to apply specific styling rules to selected elements while leaving others unchanged. This approach is essential for creating sophisticated, maintainable websites where different elements serve different purposes and require distinct visual treatment.

    To implement class-based styling, you'll add a class attribute to any HTML tag, then create corresponding CSS rules that target those classes. This two-step process gives you granular control over your design while keeping your HTML semantic and your CSS organized.

    1. Locate the three paragraphs containing the text This report was written by… — these represent author attribution lines that should be styled differently from body text. Find the first instance (approximately line 36).
    2. On the opening p tag, add the class="author" attribute as shown in bold below:

      <p class="author">This report was written by <a href="https://www.theonion.com" target="_blank">The Onion</a></p>

      NOTE: CSS class names are entirely custom — there are no predefined options. Choose names that describe the element's purpose or content rather than its appearance. For example, author is preferable to small-gray-text because it remains meaningful even if you later change the visual styling. This semantic naming approach is a hallmark of professional web development and makes your code more maintainable over time.

    3. Now that you've created a way to target this specific paragraph, you can define a CSS rule to control its appearance. In the style section, add the following code below your existing p selector. Pay close attention to the period (.) before author — this dot is crucial as it tells the browser you're creating a class selector:

      p {
            font-family: Verdana, sans-serif;
            font-size: 14px;
            line-height: 25px;
         }
         .author {
            font-size: 10px;
            text-transform: uppercase;
            font-weight: bold;
            color: #a18f81;
         }
      </style>
    4. Save the file to preserve your changes.
    5. Return to your browser and refresh the page. You should now see that only the first THIS REPORT WAS WRITTEN BY text displays in uppercase with the sand brown color, while other paragraphs remain unchanged. This demonstrates how class selectors override tag selectors for specific elements.
    6. Return to index.html in your code editor to continue the implementation.
    7. One of the key advantages of CSS classes is reusability — you can apply the same class to multiple elements without duplicating code. Find the second This report was written… paragraph (around line 48) and add the class="author" attribute as shown in bold:

      <p>The new regulation, SEC rule 206(b)-7, will reportedly target Wall Street executives who accept disgustingly bloated annual payouts, forcing them to raise and then lower their shoulders in a manner that conveys a mild degree of humility or a sense of "Aw, shucks. Who? Me?"</p>
      <p class="author">This report was written by <a href="https://www.theonion.com" target="_blank">The Onion</a></p>
    8. Complete the pattern by finding the final This report was written… paragraph near the bottom of the file and adding the same class attribute:

      <p class="author">This report was inspired by, but not written by <a href="https://www.theonion.com" target="_blank">The Onion</a></p>
      </body>
      </html>
    9. Save the file to apply your changes.

    10. Return to your browser and refresh the page. You should now see consistent author styling applied to all three attribution paragraphs, demonstrating how a single CSS class can efficiently style multiple elements throughout your document.

    Tag Selectors vs Class Selectors

    FeatureTag SelectorsClass Selectors
    ScopeAll instances of tagSpecific elements only
    Syntaxp { }.classname { }
    SpecificityLower priorityHigher priority
    ReusabilityAutomatic on all tagsApplied where needed
    Recommended: Use class selectors when you need targeted styling that differs from the default tag behavior.
    Class Naming Best Practice

    Choose class names that describe what the element IS (like 'author') rather than how it LOOKS (like 'uppercase'). This maintains flexibility if you change styling later.

    Implementing Your First Class Selector

    1

    Add Class Attribute

    Find the first 'This report was written by...' paragraph and add class="author" to the opening p tag.

    2

    Create CSS Rule

    In the style section, add .author selector with font-size: 10px, text-transform: uppercase, font-weight: bold, and color: #a18f81.

    3

    Test and Verify

    Save the file and reload in browser to see the first author paragraph styled differently from regular paragraphs.

    The Span Tag

    While classes work perfectly with existing HTML tags like paragraphs and headings, you'll often need to style just part of an element's content. This is where the span tag becomes invaluable. The span element is a generic inline container that has no semantic meaning by itself — its sole purpose is to provide a hook for CSS styling. Think of it as a highlighting marker that you can place around any portion of text to apply specific styling without affecting the document's structure or meaning.

    1. Return to index.html in your code editor to implement this technique.
    2. Let's create visual hierarchy within the main heading by making the introductory text more subtle. Since we need to style only part of the h1 content, we'll wrap the target text in a <span> tag with an appropriate class.

      Locate the h1 element near the beginning of the body section and modify it as shown in bold:

      <h1>
         <span class="heading-muted"> Latest News from The Onion:</span><br>
         Today's Top National Headlines
      </h1>

      NOTE: CSS class names are case-sensitive and must follow specific naming conventions. They cannot contain spaces or most special characters — use hyphens or underscores to separate words. The class name heading-muted clearly describes the visual effect we're creating, making the code self-documenting and easier to maintain.

    3. Now create the CSS rule to style your new class. Add the following code below your existing .author selector:

      .author {
            font-size: 10px;
            text-transform: uppercase;
            font-weight: bold;
            color:#a18f81;
         }
         .heading-muted {
            opacity:.5;
         }
      </style>

      NOTE: The opacity property accepts values between 0 and 1, where 1 represents fully opaque (100% visible) and 0 represents completely transparent (invisible). Decimal values like .5 or 0.5 (the leading zero is optional) create partial transparency — in this case, 50% opacity. This technique is particularly useful for creating visual hierarchy and subtle emphasis effects that feel natural and professional.

    4. Save your file to apply the changes.
    5. Return to your browser and refresh the page. The text Latest News from The Onion: should now appear lighter than the main headline text. This transparency effect creates visual hierarchy by reducing the prominence of the introductory text while maintaining readability against the white background.

    Understanding the Span Element

    Purpose

    Span is an inline HTML element used to group text or other inline elements for styling purposes without affecting layout.

    Use Cases

    Perfect for applying styles to portions of text within larger elements, like making part of a heading different.

    CSS Properties

    Commonly used with opacity, color, font-weight, and other styling properties to create visual emphasis or hierarchy.

    CSS Opacity Values Guide

    Fully Visible
    100
    Slightly Faded (0.8)
    80
    Half Transparent (0.5)
    50
    Very Faded (0.2)
    20
    Invisible
    0
    Class Naming Rules

    Class names are case sensitive and cannot contain spaces or special characters except hyphens and underscores. Use descriptive names like 'heading-muted' instead of generic names.

    Key Takeaways

    1Class attributes allow you to target specific HTML elements for custom styling while leaving others with default tag selector styles
    2CSS class selectors use dot notation (.classname) and have higher specificity than tag selectors, enabling style overrides
    3Class names should be semantic and descriptive of the element's purpose rather than its appearance for better maintainability
    4The same class can be applied to multiple elements, making it efficient for styling repeated design patterns
    5Span tags provide a way to apply classes to inline portions of text without affecting document structure
    6CSS opacity property accepts decimal values between 0 and 1, where 1 is fully opaque and 0 is completely transparent
    7Class names are case sensitive and must follow naming conventions excluding spaces and most special characters
    8The combination of class selectors and semantic HTML creates flexible, maintainable styling systems for web development

    RELATED ARTICLES