Attribute Selectors: Targeting Elements with [attr], ^=, $=, and *=
Attribute Selectors: Targeting Elements with [attr], ^=, $=, and *=
Welcome to CSS for Intermediate (Level 2)! 🚀
In Level 1, you learned how to select elements by tag name (p), class name (.card), and ID (#header).
While classes are great, writing classes for every single variation quickly clutters your HTML: <input type="text" class="input input-text input-required input-disabled"> 😵
HTML tags already carry a treasure trove of information inside their attributes: type, href, target, disabled, required, download, and custom data-* attributes.
With CSS Attribute Selectors, you can directly target elements based on what attributes they possess or what text their attributes contain!
In this lesson, you will master:
- 1Basic attribute presence selection (
[disabled],[required]) - 2Exact value matching (
[type="email"]) - 3The 3 powerful substring matching operators:
^=(Starts with)$=(Ends with)*=(Contains anywhere)
- 1Case-insensitive matching with the
iflag - 2Real-world UI patterns: Auto-styling PDF download links and custom form inputs
The School Library Roll-Call Analogy 📚
Imagine a school librarian searching the Student Admission Database:
+-------------------------------------------------------------------------+ | ATTRIBUTE SELECTORS IN A SCHOOL DATABASE | +-------------------------------------------------------------------------+ | 1. [scholarship] (PRESENCE) | | "Find all students who have a scholarship flag on their file, | | regardless of the scholarship amount." | | | | 2. [section="10-A"] (EXACT MATCH) | | "Find students whose class section is EXACTLY '10-A'." | | | | 3. [roll^="2026"] (STARTS WITH: ^=) | | "Find all students whose roll number starts with the year '2026'!" | | | | 4. [email$="@school.edu"] (ENDS WITH: $=) | | "Find all users whose email ends with the official '@school.edu' | | domain extension!" | | | | 5. [subjects*="Bio"] (CONTAINS: *=) | | "Find any student who has 'Bio' anywhere in their subject list!" | +-------------------------------------------------------------------------+
1. Attribute Presence: [attribute]
Matches any element that simply has the specified attribute present, regardless of what its value is:
2. Exact Value Matching: [attribute="value"]
Matches elements where the attribute value is an exact, character-for-character match:
3. The 3 Substring Operators (^=, $=, *=)
Modern websites dynamically generate URLs and IDs. You often cannot predict the exact full string, but you know how it begins, ends, or what word it contains!
Operator A: Starts With (^=)
Matches when the attribute value begins with the specified string:
Operator B: Ends With ($=)
Matches when the attribute value ends with the specified string:
This is one of the most beloved tricks in professional web design: Automatically styling download file links by their extension!
Operator C: Contains Anywhere (*=)
Matches when the specified string appears anywhere inside the attribute value:
4. Case-Insensitive Matching with the i Flag
By default, attribute values in CSS can be case-sensitive depending on the attribute. If a user uploads a file with .PDF in uppercase, a[href$=".pdf"] might fail!
To force case-insensitive matching, add the i modifier before the closing bracket:
Attribute Selectors Quick Reference Table 📊
| Selector | Meaning | Example | Real-World Use Case |
|---|---|---|---|
[attr] | Attribute is present | input[disabled] | Styling disabled form controls |
[attr="val"] | Exact match | input[type="radio"] | Styling radio buttons |
[attr^="val"] | Starts with | a[href^="https://"] | Styling external secure links |
[attr$="val"] | Ends with | a[href$=".pdf"] | Auto-detecting document downloads |
[attr*="val"] | Contains anywhere | a[href*="youtube"] | Video link badges |
[attr~="val"] | Space-separated word | [data-tags~="maths"] | Filtering custom tag lists |
[attr="val" i] | Case-insensitive | a[href$=".jpg" i] | Catching both .jpg and .JPG |
Common Mistakes Beginners Make ❌
| Bad Practice ❌ | Why It Fails ⚠️ | Better Approach ✅ |
|---|---|---|
Writing input[required="true"] | HTML boolean attributes like required or disabled do not need a value. | Just write input[required] or button[disabled]. |
Confusing ^= (starts with) and $= (ends with) | Writing a[href^=".pdf"] looks for links starting with .pdf, matching zero URLs! | Use $= for file extensions: a[href$=".pdf"]. |
| Forgetting quotes around URLs with special characters | While simple values work without quotes, values with slashes (https://) can cause parsing errors. | Always wrap attribute values in quotes: [href^="https://"]. |
Not adding the i flag for file extensions | Misses downloads ending with capital .PDF or .PNG. | Add i: a[href$=".pdf" i]. |
Summary Cheat Sheet 📌
- Attribute selectors target HTML elements directly by their attributes without polluting markup with extra classes.
[attr]checks presence;[attr="val"]checks exact equality.- The Substring Trio:
^== Starts with (href^="https://")$== Ends with (href$=".pdf")- *`=
** = Contains anywhere (href*="portal"`) imodifier: Makes substring comparison case-insensitive.
Multiple Choice Questions
1. Which CSS selector selects all hyperlink elements whose href attribute ends with .pdf?
A. a[href^=".pdf"] B. a[href$=".pdf"] C. a[href*=".pdf"] D. a.pdf-file Answer: B Explanation: The dollar symbol ($=) is the "ends with" attribute selector in CSS, perfect for targeting file extensions.
2. What does the caret symbol (^=) signify in an attribute selector like a[href^="https://"]?
A. The attribute value must contain the substring anywhere B. The attribute value must begin with "https://" C. The attribute value must be uppercase D. The attribute value is optional Answer: B Explanation: ^= matches any attribute value that starts with the specified prefix string.
3. How do you ensure that a file extension selector matches both .pdf and uppercase .PDF?
A. Add the i modifier before the closing bracket: a[href$=".pdf" i] B. Write two separate CSS files C. Set text-transform: uppercase; D. Use !important Answer: A Explanation: The i flag placed inside an attribute selector forces case-insensitive string matching.
4. Which of the following is the cleanest way to style all required form input fields with a red border without adding classes?
A. input.must-fill { border-color: red; } B. input[required] { border-color: red; } C. input[status="mandatory"] { border-color: red; } D. input:has-text { border-color: red; } Answer: B Explanation: The presence selector input[required] directly matches any input carrying the standard HTML5 required attribute.
5. What does the asterisk (*=) operator match in a[href*="wikipedia"]?
A. Only links that start with "wikipedia" B. Only links that end with "wikipedia" C. Any link where the word "wikipedia" appears anywhere inside the href attribute value D. Links that have exactly 9 characters Answer: C Explanation: The *= operator is the "contains" selector, matching occurrences of the substring anywhere within the attribute value.
Practice Challenge (Try It Yourself)
- 1Create an HTML file named
school-downloads-center.html. - 2Build an attractive school downloads center where links automatically receive appropriate brand colors and icons based entirely on attribute selectors:
- 1Open this file in your browser to observe how attribute selectors automatically decorate different file types with zero redundant class names! 🎯
Child, Descendant, and Sibling Selectors: Navigating the DOM Tree
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| None | Child, Descendant, and Sibling Selectors: Navigating the DOM Tree |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.