Tutorials CSS Attribute Selectors
Ch 36 / 60
Chapter 36 Intermediate 8 min read CSS

CSS Attribute Selectors

Attribute selectors are written inside square brackets [ ] and match elements based on the presence, exact value, or partial value of their HTML attributes — without needing a class or ID. They power patterns like styling external links differently, auto-decorating file download links, theming buttons via data-* attributes, and flagging missing accessibility attributes — all in pure CSS.

What you'll learn
[attr] — presence
[attr=val] — exact match
[attr^=val] — begins with
[attr$=val] — ends with
[attr*=val] — contains
[attr~=val], [attr|=val], case i flag

All 7 Attribute Selector Types

Every attribute selector uses square brackets. The operator between the attribute name and value determines what kind of match is performed:

[attr]
Presence
Element has the attribute — any value, even empty.
[attr=val]
Exact match
Value is exactly val, case-sensitive.
[attr^=val]
Begins with
Value starts with val.
[attr$=val]
Ends with
Value ends with val.
[attr*=val]
Contains
Value contains val as a substring anywhere.
[attr~=val]
Word match
Space-separated list contains the word val exactly — same as a class selector.
[attr|=val]
Hyphen prefix
Exactly val or starts with val-. Designed for language codes.

[attr] — Presence Selector

[attr]
Matches any element that has the attribute, regardless of its value
Live demo — elements with href are blue, plain anchors are grey
Has href ✓ href="#" ✓ No href — grey Has title attr No title
✓ Matches [href]
✓<a href="https://...">
✓<a href="#">
✓<a href=""> (empty value)
✗ Does NOT match [href]
✗<a> (no href at all)
✗<span>
✗<div href="..."> if selector is a[href]
CSS — [attr] presence
/* Matches elements that HAVE the attribute */
a[href]             { color: #264de4; }         /* any link with href */
img[alt]            { outline: none; }           /* images WITH alt */
img:not([alt])      { outline: 3px solid red; }  /* flag MISSING alt — a11y */
input[disabled]     { opacity: .5; }
button[disabled]    { cursor: not-allowed; }

/* Without element prefix — any element with the attribute */
[hidden]            { display: none; }
[data-tooltip]      { cursor: help; position: relative; }
[aria-required]     { border-color: #f97316; }
[readonly]          { background: rgba(0,0,0,.04); }

/* Plain anchor vs link */
a:not([href])       { cursor: default; color: inherit; }

[attr=val] — Exact Match

[attr=val]
Attribute value is exactly equal to val — full string, case-sensitive
Live demo — inputs styled by type value
Button variants via data-variant attribute
✓ Matches [type="submit"]
✓<input type="submit">
✓<button type="submit">
✗ Does NOT match
✗<input type="Submit"> (case)
✗<input type="submit button">
CSS — [attr=val] exact match
/* Input type styling */
input[type="text"]      { border: 2px solid #264de4; }
input[type="email"]     { border: 2px solid #22c55e; }
input[type="password"]  { border: 2px solid #ef4444; }
input[type="checkbox"]  { accent-color: #264de4; }
input[type="submit"]    { background: #264de4; color: #fff; }

/* data-attribute theming — no extra classes needed */
[data-variant="primary"]   { background: #264de4; color: #fff; }
[data-variant="danger"]    { background: #ef4444; color: #fff; }
[data-size="sm"]           { font-size: .875rem; }
[data-size="lg"]           { font-size: 1.25rem; }

/* ARIA role styling */
[role="button"]    { cursor: pointer; }
[role="tabpanel"]  { padding: 1rem; }

/* Case-insensitive with i flag */
input[type="TEXT" i]    { }  /* matches text, TEXT, Text */

[attr^=val] — Begins With

[attr^=val]
Value starts with val (^ = "starts at beginning" — like regex)
Live demo — links styled by URL protocol
✓ Matches [href^="https"]
✓href="https://example.com"
✓href="https://a.b/c?d=1#e"
✗ Does NOT match
✗href="http://example.com"
✗href="//example.com"
CSS — [attr^=val] begins with
/* Links by URL protocol */
a[href^="https"]   { color: #264de4; }   /* secure https */
a[href^="http:"]   { color: #f97316; }   /* insecure http */
a[href^="mailto"]  { color: #22c55e; }
a[href^="tel"]     { color: #a855f7; }
a[href^="#"]       { color: #94a3b8; }   /* in-page anchors */

/* Prepend icon via ::before */
a[href^="https"]::before  { content: "🔒 "; }
a[href^="mailto"]::before { content: "✉ "; }
a[href^="tel"]::before    { content: "📞 "; }

/* Utility — class names prefixed with "icon-" */
[class^="icon-"]  { display: inline-block; width: 24px; }
[id^="section-"]  { scroll-margin-top: 80px; }

/* Dev / testing helpers */
[data-testid^="btn"] { border: 2px dashed red; }

[attr$=val] — Ends With

[attr$=val]
Value ends with val ($ = "end" — like regex dollar sign)
Live demo — download links by file extension
✓ Matches [href$=".pdf"]
✓href="report.pdf"
✓href="/docs/guide.pdf"
✗ Does NOT match
✗href="report.pdf.bak"
✗href="report.PDF" (case)
CSS — [attr$=val] ends with
/* File type links */
a[href$=".pdf"]   { color: #ef4444; }
a[href$=".zip"]   { color: #22c55e; }
a[href$=".png"],
a[href$=".jpg"],
a[href$=".webp"]  { color: #f97316; }

/* Append file type label */
a[href$=".pdf"]::after  { content: " (PDF)"; font-size: .8em; }
a[href$=".zip"]::after  { content: " ↓"; }

/* Case-insensitive — matches .pdf AND .PDF */
a[href$=".pdf" i] { color: #ef4444; }

/* Image attributes */
img[src$=".svg"]  { width: auto; }
img[src$="avatar.png"] { border-radius: 50%; }

/* Scripts */
script[src$=".min.js"] { }  /* minified scripts */

[attr*=val] — Contains

[attr*=val]
Value contains val as a substring anywhere — the broadest match
Live demo — links containing "github" → purple 🐙
✓ Matches [href*="github"]
✓href="https://github.com"
✓href="https://api.github.com"
✓href="my-github-clone"
✗ Does NOT match
✗href="https://gitlab.com"
✗href="https://GITHUB.COM" (case)
CSS — [attr*=val] contains
/* Domain matching */
a[href*="github.com"]   { color: #a855f7; }
a[href*="youtube.com"]  { color: #ef4444; }
a[href*="linkedin.com"] { color: #0a66c2; }

/* Social link icons */
a[href*="github.com"]::before  { content: "🐙 "; }
a[href*="youtube.com"]::before { content: "▶ "; }

/* Utility class patterns */
[class*="flex"]    { display: flex; }
[class*="btn-"]    { padding: .5rem 1rem; }

/* Case-insensitive social links */
a[href*="linkedin" i] { color: #0a66c2; }

/* ⚠ Warning: [class*="btn"] also matches btn-group, mybtn, btn_icon */

[attr~=val] Word Match & [attr|=val] Hyphen Prefix

[attr~=val]
Word in space-separated list

Matches if the attribute is a space-separated list and one of those words is exactly val. This is how the CSS class selector (.name) works internally — they are equivalent.

Live demo — [class~="featured"] matches only the word
class="card featured" ⭐
class="featured hero" ⭐
class="card" (no match)
class="btn-featured" (no match)
✓ Matches [class~="featured"]
✓"featured"
✓"card featured"
✓"a featured b"
✗ Does NOT match
✗"btn-featured"
✗"myfeatured"
[attr|=val]
Exactly val or starts with val-

Matches if the value is exactly val OR starts with val- (with a hyphen). Designed for language sub-codes like en-US.

Live demo — lang attribute
en en-US en-GB fr fr-CA de de-AT

[lang|="en"] → blue · [lang|="fr"] → orange · [lang|="de"] → green

✓ Matches [lang|="en"]
✓lang="en"
✓lang="en-US"
✓lang="en-GB"
✗ Does NOT match
✗lang="english"
✗lang="en_US" (underscore)
CSS — [attr~=val] and [attr|=val]
/* ── [attr~=val] — word in space-separated list ── */
[class~="featured"]   { border: 2px solid gold; }
[rel~="noopener"]     { }  /* <a rel="noopener noreferrer"> */
[aria-label~="close"] { cursor: pointer; }

/* [class~="btn"] is identical to .btn */
[class~="btn"]  { }  /* ← same result as */
.btn            { }  /* ← this */

/* ── [attr|=val] — exactly val or starts with val- ── */
[lang|="en"]  { font-family: Georgia, serif; }
/* matches: lang="en", lang="en-US", lang="en-GB"
   does NOT match: lang="english" */

[lang|="fr"]  { quotes: "«" "»"; }
/* matches: lang="fr", lang="fr-CA", lang="fr-CH" */

/* Version attributes */
[data-version|="2"]  { }  /* "2" or "2-beta" or "2-rc1" */

Case Sensitivity & Specificity

Case Sensitivity

Attribute values are case-sensitive in HTML5 by default. Append the i flag (separated by a space) before the closing bracket to match case-insensitively:

[type="EMAIL"]      /* ✗ won't match type="email" */
[type="email" i]    /* ✓ matches email, EMAIL, Email */
[href$=".PDF" i]    /* ✓ matches .pdf, .PDF, .Pdf */
[lang|="EN" i]      /* ✓ matches en, EN, En, en-US */
Specificity = (0,1,0)

Each attribute selector contributes (0,1,0) — the same as a class selector. Chaining adds up:

a                                        /* (0,0,1) — element */
a[href]                                  /* (0,1,1) — attr + element */
.link                                    /* (0,1,0) — class */
a.link[href]                             /* (0,2,1) — class + attr + elem */
input[type="text"][required]             /* (0,2,1) — two attrs + element */
CSS — i flag and chaining
/* i flag — case-insensitive matching */
a[href$=".pdf" i]         { color: #ef4444; }  /* .pdf OR .PDF */
input[type="text" i]      { }  /* text, TEXT, Text */
[lang|="en" i]            { }  /* en, EN, en-US, EN-us */

/* Chaining multiple attribute selectors */
input[type="text"][required]     { border-color: #f97316; }
a[href^="https"][target="_blank"] { color: #264de4; }  /* (0,2,1) */
img[src$=".jpg"][alt]            { border-radius: 4px; }

/* Combining with pseudo-classes and pseudo-elements */
a[href^="https"]:hover          { text-decoration: underline; }
a[href$=".pdf"]::after          { content: " ↓"; }
input[disabled]:not([readonly]) { opacity: .4; }

Complete Reference

Selector Name Matches when attribute value… Example
[attr] Presence Exists (any value, even empty) img:not([alt])
[attr=val] Exact Is exactly val input[type="email"]
[attr^=val] Begins with Starts with val a[href^="https"]
[attr$=val] Ends with Ends with val a[href$=".pdf"]
[attr*=val] Contains Contains val anywhere a[href*="github"]
[attr~=val] Word match Is a space-separated list containing val as a whole word [class~="active"]
[attr|=val] Hyphen prefix Is exactly val or starts with val- [lang|="en"]
[attr=val i] Case-insensitive Above match, case-insensitive a[href$=".PDF" i]
Free Resource
CSS3 Cheat Sheet — All Properties & Selectors
Complete reference covering all CSS attribute selectors, pseudo-classes and pseudo-elements.
Download PDF

Try It Yourself

All 7 selector types in one editor. Change the attribute values in the HTML to see the selectors respond live:

Live Editor
✎ Editor
👁 Preview
Featured Course — Enroll Now
Modern Web Development With AI
Master HTML, CSS, JavaScript, React and Node.js with real projects and placement support.
120+
Chapters
40 hrs
Content
10 Real
Projects
4.9 ⭐
Rating
HTML5CSS3JavaScriptReact.jsNode.jsTailwind CSSAI Tools

Quick Check — Chapter 36

Questions & Answers
Both deal with partial value matching but operate differently:

[attr*=val] — substring match: Matches if val appears anywhere in the attribute value as a substring. [class*="btn"] matches class="btn", class="btn-primary", class="mybtn", class="btn_group" — literally any string containing "btn".

[attr~=val] — word match: Matches only if the attribute is a space-separated list and one of the words is exactly val. [class~="btn"] matches class="btn" and class="btn active", but NOT class="btn-primary" because "btn-primary" is not the same word as "btn".

In fact, [class~="btn"] is exactly equivalent to the class selector .btn. Use ~= for whole-word matching in lists; use *= for substring matching anywhere.
Combine the presence selector with :not():

img:not([alt]) { outline: 3px solid red; }

This selects every image that does not have an alt attribute and gives it a red outline — visually obvious during development.

You can also distinguish between three states:
— img:not([alt]) — no alt attribute at all (very bad — screen readers read out the full src URL)
— img[alt=""] — empty alt (correct for decorative images — screen readers skip it)
— img[alt] — has alt attribute (could still be empty or too generic)

This pattern is popular in CSS development linters and browser dev tools for surfacing accessibility issues without JavaScript.
The i flag makes value matching case-insensitive. Place it before the closing bracket, separated by a space:

a[href$=".pdf" i] — matches .pdf, .PDF, .Pdf

By default in HTML5 attribute values are case-sensitive, so [type="EMAIL"] would NOT match type="email".

Use the i flag when attribute values might be submitted in mixed case — file extensions (.PDF vs .pdf), URL paths, or language codes. It works with all seven operator types.
Each attribute selector contributes (0,1,0) — the same as a class selector. When you chain multiple selectors together, their specificities add:

— a → (0,0,1) — element only
— a[href] → (0,1,1) — attribute + element
— input[type="text"][required] → (0,2,1) — two attributes + element
— a[href^="https"][target="_blank"] → (0,2,1) — two attributes + element

This is exactly the same calculation as chaining class selectors: .btn.primary → (0,2,0).
[attr|=val] matches if the value is exactly val OR starts with val- (note: hyphen required). It was designed specifically for language attribute matching.

Key difference from [attr^=val]:
— [lang^="en"] matches: en, en-US, en-GB, AND also enjoy, ending
— [lang|="en"] matches: en, en-US, en-GB ONLY — not enjoy or ending

The |= operator is precise: any suffix after the value must start with a hyphen. This makes it perfect for language subtags where you want to target fr, fr-CA, and fr-CH, but not strings that happen to begin with "fr" like "french".
Multiple Choice Questions
Question 1 of 5
Which selector correctly flags all images with a missing alt attribute?
Question 2 of 5
Which selector targets HTTPS links that also open in a new tab?
Question 3 of 5
[class~="active"] is equivalent to which other CSS selector?
Question 4 of 5
Which selector matches lang="fr", lang="fr-CA" but NOT lang="french"?
Question 5 of 5
What is the specificity of input[type="text"][required]?
Chapter Summary
  • Attribute selectors use [ ] brackets. Specificity = (0,1,0) — same as a class selector. They require no class or ID in the HTML.
  • [attr] — presence: element has the attribute. Key use: img:not([alt]) to flag missing alt text.
  • [attr=val] — exact match. Most common uses: input[type="email"], [data-variant="danger"].
  • [attr^=val] — begins with. Style links by protocol: a[href^="https"], a[href^="mailto"].
  • [attr$=val] — ends with. Style download links: a[href$=".pdf"], a[href$=".zip"].
  • [attr*=val] — contains substring. Domain matching: a[href*="github.com"]. Broadest match — use carefully.
  • [attr~=val] — word in space-separated list. Equivalent to class selector .val. Does not match hyphenated variants.
  • [attr|=val] — exactly val or starts with val- (hyphen). Designed for language codes: [lang|="en"] matches en, en-US, en-GB.
  • Case sensitivity: case-sensitive by default. Append i flag: a[href$=".pdf" i].
  • Chaining: multiple selectors add specificity: input[type="text"][required] → (0,2,1).
~8 min read
Intermediate level
Chapter 36 of 60

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel