Attribute selectors
Definition and purpose
Attribute selectors match elements based on the presence or value of an HTML attribute. They are useful when markup already expresses a state, language or link destination. A selector examines the actual attribute string, not the browser’s interpreted URL.
Attribute patterns
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> a { color: navy; } a[href$=".pdf"] { color: green; } [lang|="en"] { background-color: white; } </style> </head> <body> <a id="a" href="https://example.test/guide.pdf">Guide</a> <a id="b" href="guide.html">Local</a> <span id="c" lang="en-GB">English</span> </body></html>The suffix matches the literal PDF URL and the language selector matches en-GB.
Syntax and mental model
[disabled] tests presence; [type="email"] tests equality. [class~="note"] matches a whitespace-separated token, [lang|="en"] matches en or en- followed by a suffix, [href^="https://"] tests prefix, [href$=".pdf"] suffix, and [href*="docs"] substring. The i flag requests ASCII case-insensitive matching; s requests case-sensitive matching where supported. Default sensitivity depends on the attribute and document language. Combine with a type selector to narrow scope.
Token versus substring
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> [data-tags~="note"] { color: green; } [data-tags*="note"] { background-color: white; } [data-state="ready" i] { color: navy; } </style> </head> <body> <p id="a" data-tags="note urgent">A</p> <p id="b" data-tags="notebook">B</p> <p id="c" data-state="READY">C</p> </body></html>A has the exact token; B only has the substring. The i flag matches READY.
Common mistakes
Do not assume an https prefix proves a link is external or trustworthy. Relative URLs and same-origin absolute URLs exist. Use explicit metadata when you need a reliable distinction; never use CSS selectors as a security control.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Sibling combinators. Next lesson: Structural pseudo-classes.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Attribute selectors — knowledge check
Five questions on attribute selectors.
Which selector tests attribute presence?
Which matches data-tags="note urgent" but not notebook?
Which tests a literal suffix .pdf?
What does the i flag request?
Does href starting with https:// prove the link is external?