Attribute Selectors: Presence, Exact, Partial Matches and Case Sensitivity
Selecting elements by their attributes: [attr] for presence, [attr=value] for exact values, ~= for words, |= for language codes, ^=, $= and *= for prefixes, suffixes and substrings, the i and s case flags, quoting rules, and practical uses such as external links, file types and ARIA states.
kvi5hnuCode Sprout team member8 min readOn this page
Classes are attributes you control, but HTML elements carry many other attributes: href, type, lang, disabled, aria-expanded, data-* and more. Attribute selectors match elements by those attributes and their values. They let you style a link by where it points, an input by its type, or a button by its ARIA state, without adding classes to the HTML.
Presence: [attr]
Square brackets around an attribute name match every element that has that attribute, whatever its value, even an empty one:
[disabled] { opacity: 0.5; }
abbr[title] { text-decoration: underline dotted; cursor: help; }
img[alt] { } /* images that have an alt attribute */
This is how you style boolean attributes, such as disabled, required, hidden, open and multiple, which are present or absent. img:not([alt]) finds images missing alternative text, which is a useful check during development (:not() is in article 12).
Exact value: [attr="value"]
[attr="value"] matches when the attribute's whole value is exactly value:
input[type="email"] { background-image: url("/icons/mail.svg"); }
a[href="/"] { font-weight: 700; } /* links to the home page */
button[aria-expanded="true"] { background: #f4efe6; }
The value must match completely. [class="book"] doesn't match class="book featured", because the whole value is "book featured", which is why classes use .book (or [class~="book"]) instead.
Quotes around the value are optional when it's a valid identifier, such as [type=email], but required when it contains spaces, starts with a digit, or contains characters such as / or :. Always quoting is the simplest habit.
Combining attribute selectors
Several attribute selectors in a compound must all match:
a[href][target="_blank"] { } /* links that open a new tab */
input[type="checkbox"][checked] { } /* checkboxes checked by default in the HTML */
Attribute selectors match the attribute in the markup, not the element's live state. The checked attribute reflects only the initial state written in the HTML. When the user clicks, the attribute doesn't change, so use the :checked pseudo-class for the current state (article 11). The same applies to value: input[value=""] doesn't follow what the user types. Use :placeholder-shown or the validity pseudo-classes for that.
![Two pairs of checkboxes after a script clicked both, so Gift wrap, checked in the HTML, is now unchecked, and Newsletter is now checked. With input[checked], the highlighted row is still Gift wrap, the one whose HTML had the attribute. With input, the highlighted row is Newsletter, the one that's actually checked](https://code-sprout-content.laxmi.solutions/asset/2026/11/css-attribute-vs-state-render-spcqpwyxm72lqn6m.png)
The left panel highlights the wrong row: the checked attribute still says what the HTML said when the page loaded.
Partial values
Five operators match part of a value:
| Selector | Matches when the value... | Example match |
|---|---|---|
[attr~="word"] | contains word as a whole space-separated word | [class~="sale"] on class="book sale" |
[attr|="en"] | is exactly en or starts with en- | [lang|="en"] on lang="en-GB" |
[attr^="text"] | starts with text | [href^="https:"] |
[attr$="text"] | ends with text | [href$=".pdf"] |
[attr*="text"] | contains text anywhere | [href*="harborbooks"] |
(The table escapes the pipe character, which is written |= in CSS.)
~=treats the value as a space-separated list, as the class attribute is..saleis effectively[class~="sale"]. It's useful for other list-valued attributes, such asrel="noopener noreferrer".|=was designed for language codes.[lang|="pt"]matchespt,pt-BRandpt-PT, but notptx. For languages, the:lang()pseudo-class is usually better, because it also matches elements that inherit a language from an ancestor (article 11).^=,$=and*=are plain substring tests, and are the ones you'll use most.
a { color: #1d4ed8; }
a[href^="http"]::after { content: " ↗"; }
a[href^="http"][href*="harborbooks.example"]::after { content: ""; }
a[href$=".pdf"]::before { content: "PDF "; font-size: 0.75em; font-weight: 700;
background: #b3261e; color: white; padding: 0 0.25em; border-radius: 3px; }
a[href^="mailto:"] { color: #2f7d4f; }
The second rule removes the arrow from links to the shop's own domain. It has two attribute selectors, so it's more specific than the first rule and wins (article 15).
Substring traps
An empty value never matches with ~=, ^=, $= or *=: [class^=""] selects nothing, which can surprise you when the value comes from a template. A ~= value containing a space never matches either, since it can't be one word.
Substring matches are literal, so they can match more than you intend:
[href*="book"]matches/books,/notebooksandebookstore.example.[href$=".pdf"]misses/report.PDF(case) and/report.pdf?download=1(query string).[class^="btn"]breaks when the element's class list is"large btn-primary", because the value starts withlarge. To match a class prefix, use[class^="btn-"], [class*=" btn-"], or better, add a real class.
![Six attribute selectors run against the same lists of values, with matches highlighted. [href^="https:"] matches only the publisher link. [href$=".pdf"] matches /files/list.pdf but not /files/REPORT.PDF or the link with ?download=1. Adding the i flag also matches REPORT.PDF. [href*="book"] matches the publisher's /books and also /notebooks. [class~="sale"] matches class="book sale" and class="sale" but not on-sale or presale. [lang|="en"] matches en, en-GB and en-US but not eng or fr](https://code-sprout-content.laxmi.solutions/asset/2026/11/css-attribute-operators-render-uep2tvd7m3uk22x4.png)
The traps from the list above are all visible here: the missed .PDF and ?download=1 links, and /notebooks caught by a search for book.
Case sensitivity: the i and s flags
Whether attribute values are case-sensitive depends on the attribute. In HTML, values of attributes with a fixed set of keywords, such as type, method, dir and lang, are matched case-insensitively. Values of attributes you invent, such as class, id, href, title and all data-* attributes, are case-sensitive.
You can override it with a flag before the closing bracket:
a[href$=".pdf" i] { } /* .pdf, .PDF and .Pdf */
[data-status="Active" i] { } /* active, ACTIVE ... */
input[type="text" s] { } /* exactly "text", not "TEXT" */
imakes the comparison case-insensitive (for ASCII letters).sforces a case-sensitive comparison, even for attributes HTML treats as case-insensitive. It works in Firefox and in Safari 27, but Chromium doesn't support it: there, the selector is invalid, so the whole rule is dropped. Avoid it, or keep it in a rule of its own.
Attribute names in HTML documents are always case-insensitive: [DATA-STATUS] matches data-status.
Practical uses
Styling state from ARIA and data attributes
Components often expose their state in attributes, which makes attribute selectors a natural way to style them. The style then follows the real state instead of a class that might fall out of sync:
.toggle { font: inherit; padding: 0.4rem 0.8rem; border: 1px solid #8a3b12;
background: white; border-radius: 999px; }
.toggle[aria-pressed="true"] { background: #8a3b12; color: white; }
.badge { padding: 0 0.4rem; border-radius: 4px; font-size: 0.85rem; }
.badge[data-stock="low"] { background: #fde7d6; color: #8a3b12; }
.badge[data-stock="out"] { background: #eee; color: #555; text-decoration: line-through; }
Form controls by type
input[type="checkbox"], input[type="radio"] { accent-color: #8a3b12; }
input:not([type]), input[type="text"], input[type="search"] { width: 100%; }
input:not([type]) catches inputs with no type attribute, which are text inputs by default.
Language and direction
[lang|="fr"] { quotes: "« " " »"; } /* French quotation marks */
[dir="rtl"] .icon-arrow { transform: scaleX(-1); }
The :lang() and :dir() pseudo-classes (article 11) are more accurate, because they use the language and direction an element inherits, not just the attribute on the element itself.
Specificity and performance
An attribute selector has the same specificity as a class, whatever the operator: [type="email"] and .email weigh the same, and so do [id="top"] and .top, even though #top is much heavier (article 15). That makes [id="..."] a way to select by ID without the ID's specificity.
Substring selectors are slightly slower than classes to match, but the difference is negligible in real pages. Choose them for clarity.
What's current
- All attribute selector operators, and the
iflag, work in every current browser. - The
sflag works in Firefox and Safari 27. Chrome and Edge treat it as an invalid selector.
Common questions
Why doesn't [class="featured"] match <div class="card featured">?
= compares the whole value, which is "card featured". Use .featured, or [class~="featured"], which matches one word in a space-separated list.
Do I need quotes around attribute values?
Only when the value isn't a valid CSS identifier: when it has spaces, starts with a digit, or contains characters such as /, . or :. [type=email] works, but [href$=.pdf] doesn't. Quoting every value avoids the question.
How do I select an element by a data-* attribute?
[data-state] for presence, [data-state="open"] for an exact value. data-* values are case-sensitive, so add i if the casing varies. Avoid styling with long data- values that mix several pieces of information: split them into separate attributes or classes.
Should I style with [aria-expanded="true"] or with a class?
Styling from ARIA attributes is a good practice when the attribute must be there anyway for accessibility: the visual state can't drift from what screen readers announce. Don't add ARIA attributes only to style with them. Use a class or a data- attribute for purely visual states.
Why doesn't input[checked] update when the user ticks the box?
The checked attribute is the default state written in the HTML. Clicking changes the element's checked property, not the attribute. Use input:checked, which matches the current state.
Summary
[attr]matches elements that have the attribute, and suits boolean attributes such asdisabledandrequired.[attr="value"]matches the whole value exactly.~=matches a whole word in a space-separated list, and|=matches a value or a value followed by a hyphen, as in language codes.^=,$=and*=test for a prefix, suffix or substring. They're literal, so watch for unintended matches.- The
iflag makes the comparison case-insensitive. HTML matches some attributes' values case-insensitively already. - Attribute selectors have the same specificity as classes, whatever the attribute, including
id. - They're well suited to styling states that live in attributes, such as ARIA states,
data-*values and form control types.
Practice questions
Write a selector for links that open in a new tab and point to another site (their href starts with http).
Answer
a[target="_blank"][href^="http"]
Both attribute selectors must match the same element.
Which of these elements does [lang|="en"] match? lang="en", lang="en-US", lang="eng", lang="fr-en".
Answer
lang="en" and lang="en-US". |= matches the exact value or the value followed by a hyphen. eng doesn't continue with a hyphen, and fr-en doesn't start with en.
A rule a[href$=".pdf"] misses some PDF links in a site. Give two likely reasons and a fix for one of them.
Answer
Some links use uppercase extensions, such as .PDF, and some have query strings or fragments after the extension, such as report.pdf?v=2. Adding the i flag fixes the case problem: a[href$=".pdf" i]. For query strings, [href*=".pdf"] is broader, at the risk of other false matches, so a class on those links is more reliable.
Which has higher specificity, #cart or [id="cart"]? Why might you choose the second?
Answer
#cart is much more specific: it's an ID selector, while [id="cart"] is an attribute selector with the specificity of a class. The attribute form selects the same element while keeping the rule easy to override.
Previous: Basic Selectors: Type, Class, ID, Universal and Grouping
Next: Combinators: Descendant, Child, Next-Sibling and Subsequent-Sibling Selectors

More in CSS Course
Quiz: CSS Delicate Details
Twenty-five questions on the edge cases that surprise experienced developers: invalid custom properties, shorthands that reset values, layer order with !important, containing blocks, margin collapsing, specificity of :is() and :where(), intrinsic minimum sizes, and more, each checked in Chrome.
Quiz: CSS Interview Questions
Thirty front-end interview questions: cascade, specificity and layers, box model and margin collapsing, stacking contexts, positioning, flexbox and grid, responsive design, custom properties, performance, accessibility, modern selectors and architecture.
Quiz: CSS Course Final Exam
Thirty questions across the whole CSS course: syntax and error handling, selectors, the cascade and layers, values and units, color, the box model, backgrounds, positioning, flexbox, grid, responsive design, typography, generated content, effects, transforms, motion and architecture.
Quiz: CSS Architecture, Tooling and Debugging (CSS Part 17)
Twenty questions on modular CSS and BEM, layering a stylesheet, design tokens and theming, pattern libraries and safe refactoring, preprocessors and build tools, the at-rules reference, and debugging common CSS problems.
Discussion
Sign in to ask a question or share what you learned.