Course contentsShow
← Web Development
Lesson 122 of 2,9823. CSS FundamentalsFree lesson

Attribute Selectors

Target elements based on their attributes using various matching patterns like exact, prefix, and substring.

Attribute Selectors

What you'll learn: How to target HTML elements in CSS based on what attributes they have and what values those attributes contain.

The Core Idea

You've already learned to select elements by type (p), class (.intro), and ID (#main). But sometimes you need to target elements based on other attributes—like selecting all links that go to a PDF, or all inputs that are required. Attribute selectors let you write CSS rules that match elements based on any HTML attribute and its value.

Think of it like sorting mail: instead of just organizing by "letter" or "package" (element type), you can now sort by "has a tracking number" or "sender starts with 'A'" (attributes and their patterns).

Common Attribute Selector Patterns

Exact match: [type="email"] targets elements where the type attribute equals exactly "email"

input[type="email"] {
  border: 2px solid blue;
}

Has attribute: [required] targets any element that simply has a required attribute, regardless of value

input[required] {
  border-color: red;
}

Starts with: [href^="https"] matches when the attribute begins with the specified text

a[href^="https"] {
  color: green;
}

Ends with: [href$=".pdf"] matches when the attribute ends with the specified text

a[href$=".pdf"] {
  font-weight: bold;
}

Contains: [class*="btn"] matches when the attribute contains the text anywhere

button[class*="btn"] {
  padding: 10px;
}

When to Use Them

Attribute selectors shine when you need to style form elements differently based on their type or state, or when styling links based on where they point.

Key Takeaway: Attribute selectors let you target elements based on any HTML attribute using patterns like exact matches, prefixes, suffixes, and substrings—giving you precise control without adding extra classes.