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

Attribute Selectors: Free HTML & CSS Tutorial

Master CSS Attribute Selectors for Dynamic Link Styling

Core CSS Selectors Covered

Ends With Selector

Target attributes ending with specific values using $= syntax. Perfect for file extensions like .pdf or .jpg.

Begins With Selector

Target attributes starting with specific values using ^= syntax. Ideal for external links starting with http.

Contains Selector

Target attributes containing specific strings using *= syntax. Great for domain-specific targeting like youtube.com.

Topics Covered in This HTML & CSS Tutorial:

Adding Link Icons with Attribute Selectors, "Ends With" Attribute Selector, "Begins With" Attribute Selector, "Contains" Attribute Selector

Exercise Preview

preview attribute selectors

Link Types in This Tutorial

PDF Downloads33%
YouTube Videos33%
External Websites33%

Exercise Overview

In this exercise, you'll master one of CSS's most powerful but underutilized features: attribute selectors. By the end of this tutorial, you'll be able to automatically add contextual icons to links based on their destination type — PDFs, external sites, YouTube videos, and more — without cluttering your HTML with additional classes. This approach creates cleaner, more maintainable code while providing users with immediate visual cues about what they're about to click.

Modern web users expect this kind of visual feedback, and implementing it through attribute selectors demonstrates advanced CSS knowledge that separates professional developers from beginners.

Getting Started

Let's set up your development environment with the exercise files. We'll be working with a realistic scenario involving different link types that you'll encounter in virtually every web project.

  1. We'll be switching to a new folder of prepared files for this exercise. In your code editor, close all open files to avoid confusion and ensure you're working with the correct project context.
  2. For this exercise we'll be working with the Tahoe Attribute Selectors folder located in Desktop > Class Files > Advanced HTML CSS Class. Open that folder in your code editor if it supports folder-based workflows (like Visual Studio Code, Sublime Text, or Atom).
  3. Open index.html from the Tahoe Attribute Selectors folder to begin examining the structure we'll be enhancing.
  4. Preview index.html in a browser to understand the current user experience. This is where we left off in the previous exercise. Notice how the links at the bottom of each column lead to different types of destinations:

    • Click Download a Trail Guide to open a PDF in a new tab. (This is a single page dummy PDF file that simulates real-world documentation downloads.)
    • Click Watch a video to go to a youtube.com video in a new tab.
    • Click Book a Ski Trip to go to a website in a new tab.

    Currently, users have no visual indication of what type of content they're about to access. Let's fix that by adding intuitive icons that communicate the link destination at a glance.

  5. Leave the page open in the browser so you can see your changes in real-time as we implement them.

Setup Requirements

0/4

Analyzing the Link Structure

Before implementing our solution, we need to understand the patterns in our HTML that we can target. This analysis phase is crucial for writing efficient, scalable CSS.

  1. Return to index.html in your code editor and examine the markup structure.
  2. Near the end of each section tag, find the link above Read More and note the href attribute patterns for each:

    • href="downloads/trail-guide.pdf" — Local PDF file
    • href="https://www.youtube.com/watch?v=4zlzh3zwdgi" — YouTube video
    • href="https://www.skilaketahoe.com" — External website

    These patterns are exactly what we'll target with our attribute selectors. Notice how each link type has distinct characteristics in its href value that we can leverage.

Adding the Link Icons

We'll implement the icon system using CSS background images, which provides better semantic structure than inserting decorative images directly into the HTML. The icons we're using are optimized at 16px by 16px for crisp display across different screen densities.

Our approach will be progressive: start with general rules, then get increasingly specific as we refine the targeting.

  1. Open main.css from the css folder to begin implementing our icon system.
  2. Let's establish a foundational rule for anchor tags to display background images. Above the .book-now-btn rule, add the following new rule:

    a {
       background: url(../img/icon-pdf.png);
    }

    NOTE: We already have a rule for anchor tags elsewhere, but we'll be refining this approach with more specific selectors shortly, so we're creating a new rule for our icon system.

  3. Save the file, then reload the page in your browser to see the initial implementation.
  4. The background image appears behind the links, but it's tiling by default. This creates visual noise that we need to eliminate.
  5. Return to main.css in your code editor to refine the display behavior.
  6. Add the bold code shown to prevent image repetition:

    a {
       background: url(../img/icon-pdf.png) no-repeat;
    }
  7. Save the file, then reload the page in your browser. The icon now appears once per link, creating a cleaner appearance.
  8. Let's position the icon to the right of each link for better visual hierarchy. Go to main.css and add the positioning values:

    a {
       background: url(../img/icon-pdf.png) no-repeat right center;
    }
  9. Save the file, then reload the page in your browser to see the improved positioning.
  10. We want to display the icons at their optimal size of 16 x 16px for sharp rendering. Go to main.css and add the size specification:

    a {
       background: url(../img/icon-pdf.png) no-repeat right center / 16px;
    }
  11. Save the file and reload the page in the browser.

    The size is correct, but notice how the icon overlaps with the text. This occurs because anchor tags are inline elements by default, meaning they only occupy the space their content requires. To accommodate the icon, we need to add padding that creates dedicated space for the background image.

  12. Go to main.css and add padding to create proper spacing:

    a {
       background: url(../img/icon-pdf.png) no-repeat right center / 16px;
       padding-right: 24px;
    }

    The 24px padding provides 16px for the icon plus 8px of breathing room, creating professional visual spacing.

  13. Save the file and reload the page in the browser. Now the icons display beautifully alongside the link text without overlapping.

Icon Implementation Process

1

Add Background Image

Apply initial PDF icon using url(../img/icon-pdf.png) to all anchor tags

2

Stop Image Repetition

Add no-repeat property to prevent icon from tiling across the background

3

Position the Icon

Use right center positioning to place icon on the right side of each link

4

Set Icon Size

Define 16px dimensions using background-size property for consistent appearance

5

Add Padding Space

Apply 24px right padding to create visual space between text and icon

Icon Sizing Strategy

All icons are designed at exactly 16px by 16px to maintain visual consistency across different link types. The 24px padding provides 8px of breathing room around each icon.

Implementing Precise Targeting with Attribute Selectors

Now comes the sophisticated part: using attribute selectors to automatically apply the correct icon based on link characteristics. This approach eliminates the need for manual class assignment and creates a system that works automatically with new content.

Attribute selectors target the properties we add to HTML elements (such as href, alt, and target). By targeting the href attribute, we can create rules that automatically recognize different link types and style them appropriately.

  1. Switch back to main.css to implement our intelligent targeting system.
  2. Add [href="downloads/trail-guide.pdf"] to the a selector as shown below:

    a[href="downloads/trail-guide.pdf"] {
       background: url(../img/icon-pdf.png) no-repeat right center / 16px;
       padding-right: 24px;
    }
  3. Save the file and reload the page in the browser. Now the PDF icon only appears next to the Download a Trail Guide link, demonstrating precise targeting.

    However, this exact-match approach isn't scalable for real-world projects. If you add another PDF link with a different filename, you'd need to write another rule. Let's implement a more versatile solution that targets any PDF link by looking for the .pdf file extension.

  4. Go to main.css and edit the selector to use pattern matching:

    a[href$=".pdf"] {
       background: url(../img/icon-pdf.png) no-repeat right center / 16px;
       padding-right: 24px;
    }

    The $= operator is a "ends with" selector that matches any href attribute ending with the specified string. While = requires an exact match, $= provides flexible pattern matching. This means our rule will work for trail-guide.pdf, annual-report.pdf, or any other PDF link you add to the site.

  5. Save the file and reload the page in the browser. The functionality appears identical, but your code is now infinitely more maintainable and professional.

Selector Specificity Comparison

FeatureMethodReusabilityMaintenance
Exact MatchSingle link onlyPoor
Ends With (.pdf)All PDF filesExcellent
Class-basedManual addition neededMedium
Recommended: Attribute selectors provide the best balance of specificity and reusability

Adding External Link Recognition

Next, we'll target external links like Book a Ski Trip. External links present a different user experience consideration — they navigate users away from your site — so they deserve visual distinction. We'll target links beginning with "http" to catch both HTTP and HTTPS protocols.

  1. Return to your code editor to implement external link detection.
  2. Copy the PDF rule we just created and paste a duplicate directly below it:

    a[href$=".pdf"] {
       background: url(../img/icon-pdf.png) no-repeat right center / 16px;
       padding-right: 24px;
    }
    a[href$=".pdf"] {
       background: url(../img/icon-pdf.png) no-repeat right center / 16px;
       padding-right: 24px;
    }
  3. Edit the duplicate to target external links as shown in bold:

    a[href$=".pdf"] {
       background: url(../img/icon-pdf.png) no-repeat right center / 16px;
       padding-right: 24px;
    }
    a[href^="http"] {
       background: url(../img/icon-external-link.svg) no-repeat right center / 16px;
       padding-right: 24px;
    }

    The ^= operator is a "begins with" selector that matches any href starting with the specified string. This approach catches both HTTP and HTTPS links, making it future-proof as the web continues its transition to secure protocols. We're using an SVG icon here for crisp scaling across different display densities.

  4. Save the file and reload the page in the browser. Observe how the Book a Ski Trip link now displays the external link icon, providing users with immediate context about the navigation behavior they can expect.

Implementing YouTube-Specific Styling

Video content deserves special recognition in user interfaces. YouTube links, while technically external, represent a specific type of media consumption that users understand differently than general external websites.

  1. Notice that the external link icon currently appears next to the Watch a Video link as well, since YouTube URLs begin with "http". While accurate, we can provide more specific visual information with a YouTube-branded icon.
  2. Go to main.css in your code editor to implement YouTube-specific targeting.
  3. Copy the external link rule and paste a duplicate directly below:

    a[href^="http"] {
       background: url(../img/icon-external-link.svg) no-repeat right center / 16px;
       padding-right: 24px;
    }
    a[href^="http"] {
       background: url(../img/icon-external-link.svg) no-repeat right center / 16px;
       padding-right: 24px;
    }
  4. We want to target all YouTube links regardless of their specific URL structure, so we'll look for the distinctive "youtube.com" domain. Edit the code as shown in bold:

    a[href^="http"] {
       background: url(../img/icon-external-link.svg) no-repeat right center / 16px;
       padding-right: 24px;
    }
    a[href*="youtube.com"] {
       background: url(../img/icon-youtube.svg) no-repeat right center / 16px;
       padding-right: 24px;
    }

    The *= operator is a "contains" selector that matches any href containing the specified substring anywhere within it. The asterisk (*) is a wildcard that means the target content can appear at any position, surrounded by any other characters. This approach works for youtube.com, www.youtube.com, m.youtube.com, or any other YouTube URL variation.

  5. Save the file and reload the page in the browser. The Watch a Video link now displays the distinctive YouTube icon, providing immediate context about the media experience users can expect.

    NOTE: You might wonder why the external link icon no longer appears next to the YouTube link, even though YouTube URLs begin with "http". This demonstrates CSS specificity in action. Both the external link selector (a[href^="http"]) and the YouTube selector (a[href*="youtube.com"]) have identical specificity values, so the rule that appears later in the stylesheet (YouTube) overrides the earlier rule (external link). This cascading behavior is exactly what we want in this case, as the more specific YouTube styling provides better user context than the generic external link indicator.

Congratulations! You've implemented a sophisticated, maintainable icon system using CSS attribute selectors. This approach automatically categorizes and styles links based on their destinations, creating better user experience while keeping your HTML clean and semantic. As you encounter new link types in future projects, you can extend this system using the same principles to provide users with consistent, intuitive visual cues throughout your applications.

Key Takeaways

1Attribute selectors provide dynamic targeting without requiring manual class additions to HTML elements
2The 'ends with' selector ($=) is perfect for targeting file extensions like .pdf, .jpg, or .zip
3The 'begins with' selector (^=) effectively identifies external links by targeting http/https protocols
4The 'contains' selector (*=) allows for flexible substring matching within attribute values
5CSS rule order determines precedence when multiple selectors have equal specificity levels
6Background image positioning and padding work together to create professional-looking link icons
7Consistent icon sizing (16px) and padding (24px) maintains visual harmony across different link types
8Attribute selectors scale better than class-based approaches for systematic link categorization

RELATED ARTICLES